文件操作和找到一个字和棘手的代表

2024-10-03 11:14:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样的档案

hostname ser1-xyz
myuser   name
passwd   secret
group    1234

hostname ser2-xyz
myuser   name
passwd   secret
group    2345

我需要找到名为“ser1xyz”的主机的第一个外观行并将其修改为 “ser1”并将组值递增1

最后的文件看起来像:

^{pr2}$

目前我正在遵循代码,它可以将“ser1 xyz”修改为“ser1”

        for line in fileinput.FileInput(fn,inplace=1):
                line = line.replace(search,replace)

但是如何增加群体价值呢?在


Tags: namesecretlinegroup档案replacehostnamepasswd
1条回答
网友
1楼 · 发布于 2024-10-03 11:14:18

单程

import fileinput
f=0
for line in fileinput.input("file",inplace=0):
    if "hostname" in line and "ser1-xyz" in line:
       line=line.replace("ser1-xyz","ser1")
       f=1
    if f and "group" in line:
       a=line.rstrip().split(" ")
       a[-1]=str(int(a[-1])+1)
       line=' '.join(a)
       f=0
    print line.rstrip()

输出

^{pr2}$

inplace=0更改为inplace=1进行就地编辑。在

相关问题 更多 >