views:

47

answers:

2

Let's say I got a file with three lines of this structure:

foo
Black sheep: 500
bar

What I'd like to do is an iteration to change "Black sheep: 500" to 600, 700 and so on, replacing the old one. I can think of a way of doing it by search&replace, but I'm looking for a more elegant way by replacing a certain position (here pos.3) within the line.

For example, in awk/shellscripting, it works like this:

cat filename | awk '$1 ~ /Black:/ { print ($1, $2, 600); next }; { print $0 }'

awk looks for "Black" in the file and prints the words number one, number two and 600 as well as the rest of the file.

Is there something similar in Python?

Thank you

A: 

We can simply mimick the awk behaviour in a couple of lines :)

for line in lines:
    if line.startswith('Black'):
        line_parts = line.split()
        print line_parts[0], line_parts[1], 600
    else:
        print line

Cause that's basically what awk does, split on whitespace.

WoLpH
small difference with startswith is that, if there are white spaces before "Black", then startswith will not find it. Whereas not the case with `awk '$1 ~ /Black:/`,
ghostdog74
@user131527: That's true, splitting the line would be more accurate but most of the times not needed. Otherwise a `lstrip()` could be applied aswell.
WoLpH
Also an interesting choice, thank you too
A: 
>>> for line in open("file"):
...     sl=line.split()
...     if "Black" in sl[0] :
...         sl[2]="600"
...         line=' '.join(sl)
...     print line.rstrip()
...
foo
Black sheep: 600
bar
ghostdog74
Thank you, this works well. I extended it a bit for my purposes.