Mr. Fegur
Mr. Fegur

Reputation: 797

grep each line of a file, and increment values

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

Answers (2)

Xiphias
Xiphias

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

inspectorG4dget
inspectorG4dget

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

Related Questions