Reputation: 797
I have a file with lines:
[tree]:1,"asdf"
[box]:2,"yuio"
[bee]:10,"rtyu"
[cup]:15,"bnmv"
[tree]:13,"asdf"
and I want the output to be
[tree]:2,"asdf"
[box]:2,"yuio"
[bee]:10,"rtyu"
[cup]:15,"bnmv"
[tree]:14,"asdf"
So I need to increment the [tree] value by 1. I need some way to search each line for [tree], copy the number next to it which may be more than 2 digits, and then increment this number. I have done this in Matlab but it is painfully slow, and involves rewriting the entire file. I'm looking for a faster alternative, like a bash script or maybe something in python.
Upvotes: 0
Views: 252
Reputation: 4716
Try this:
f = file("file.txt")
for l in f:
if l[:6] == "[tree]":
s = "".join([l[:l.find(":")+1], str(int(l[l.find(":")+1:l.find(",")])+1), l[l.find(","):]])
print s
Instead of print
, do whatever you like with the result. For example, you could write it to a file again.
Upvotes: 1
Reputation: 113975
def incrementKeys(infilepath, outfilepath, keys, incrementBy):
with open(infilepath) as infile, open(outfilepath, 'w') as outfile:
for line in infile:
if any(line.startswith(key) for key in keys):
k, tail = line.split(',')
k, val = k.split(":")
val = int(val)+incrementBy
line = "%s:%d,%s\n" %(k, val, tail)
outfile.write(line)
Upvotes: 1