文件操作,并找到一个字和棘手的替换 [英] file manipulation and find a word and tricky replace

查看:159
本文介绍了文件操作,并找到一个字和棘手的替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  hostname ser1-xyz 
myuser name
passwd secret
group 1234

hostname ser2-xyz
myuser name $ b $ passwd secret $ b $ group 2345
$ b $

我需要找到名为ser1-xyz的主机的第一个外观,并将其修改为
ser1,并将其值增加1。 / p>

所以最终的文件看起来像:

  hostname ser1 
myuser名称
passwd秘密
组1235

主机名称ser2-xyz
myuser名称
passwd秘密
组2345

目前,我正在关注代码,可以将ser1-xyz修改为ser1

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

但是如何递增组值?

解决方案

单程

 导入文件输入
f = 0
用于fileinput.input中的行file,inplace = 0):
如果hostname在行中并且ser1-xyz在行中:
line = line.replace(ser1-xyz,ser1)
f = 1
如果f和group符合:
a = line.rstrip()。split()
a [-1] = str(int(a [-1 ])+ 1)
line =''.join(a)
f = 0
print line.rstrip()

输出

  $ ./python.py 
主机名称ser1
myuser name
passwd secret
group 1235
$ b $ hostname ser2-xyz
myuser name
passwd secret
group 2345

更改 inplace = 0 inplace = 1 就地编辑。


I have file something like this

hostname ser1-xyz
myuser   name
passwd   secret
group    1234

hostname ser2-xyz
myuser   name
passwd   secret
group    2345

I need to find the line first appearance of host named "ser1-xyz" and modify it as "ser1" and increment it's the group value by 1

So that final file looks like :

hostname ser1
myuser   name
passwd   secret
group    1235

hostname ser2-xyz
myuser   name
passwd   secret
group    2345

Currently I'm following code,which can modify the "ser1-xyz" into "ser1"

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

But how to increment group value?

解决方案

one way

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()

output

$ ./python.py
hostname ser1
myuser   name
passwd   secret
group    1235

hostname ser2-xyz
myuser   name
passwd   secret
group    2345

change inplace=0 to inplace=1 for inplace edit.

这篇关于文件操作,并找到一个字和棘手的替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆