Python搜索字符串并替换下一行中的字符

时间:2015-06-19 10:35:54

标签: python regex sed

在文本文件中我想搜索包含特定文本的行,并在下一行我想用#替换行的开头(注释掉):

示例 - 之前:

#test search 123
text to be commented out
#test 123

示例 - 想要:

#test search 123
#text to be commented out
#test 123

我可以通过sed:

来做到这一点
sed -i '/^#test search 123/!b; n; s/^/#/' test_file

但我想知道我是否能够在python中本地执行此操作。

2 个答案:

答案 0 :(得分:1)

import os

outfile = open('bla.txt.2', 'w')

search = "#test search 123"
flag = 0

with open('bla.txt', 'r') as f:

    for line in f:
        if flag == 1:
            mod_line = "#" + line
            outfile.write(mod_line)
            flag = 0
            continue

        outfile.write(line)
        if (search in line):
            flag = 1

outfile.close()

os.remove('bla.txt')
os.rename('bla.txt.2', 'bla.txt')

答案 1 :(得分:0)

正确的sed将是

 -y       Perform a dry run. All of the steps to build the ports and their
          dependencies are computed, but not actually performed. With the
          verbose flag, every step is reported; otherwise there is just
          one message per port, which allows you to easily determine the
          recursive deps of a port (and the order in which they will be
          built).

这可能不是大多数pythonic方式相同,特别是如果需要导入re更复杂的模式然后简单的字符串

sed -i '/pattern/ {N; s/\n/\n#/}' file