grep文件的每一行,并增加值

时间:2014-02-04 22:21:55

标签: python regex

我有一个包含行的文件:

[tree]:1,"asdf"
[box]:2,"yuio"
[bee]:10,"rtyu"
[cup]:15,"bnmv"
[tree]:13,"asdf"

我希望输出为

[tree]:2,"asdf"
[box]:2,"yuio"
[bee]:10,"rtyu"
[cup]:15,"bnmv"
[tree]:14,"asdf"

所以我需要将[tree]值递增1.我需要一些方法来搜索[tree]的每一行,复制它旁边的数字,可能超过2位数,然后递增这个数字。我已经在Matlab中完成了这个,但它很慢,并涉及重写整个文件。我正在寻找一个更快的替代方案,比如bash脚本或python中的东西。

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:1)

试试这个:

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

而不是print,用结果做任何你喜欢的事。例如,您可以再次将其写入文件。