views:

41

answers:

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?

+1  A: 

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.

ghostdog74
Wow..cool thanks It works perfectly . I'll use your code :)
lakshmipathi