0

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.

Mr. Fegur
  • 797
  • 1
  • 6
  • 18

2 Answers2

1
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)
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
1

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.

Xiphias
  • 4,468
  • 4
  • 28
  • 51