Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python搜索字符串并替换下一行中的字符_Python_Regex_Sed - Fatal编程技术网

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

Python搜索字符串并替换下一行中的字符,python,regex,sed,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中以本机方式

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

示例-之前:

#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中以本机方式完成它

正确的sed将被删除

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')
sed -i '/pattern/ {N; s/\n/\n#/}' file  
接下来的方法可能不是最类似于python的方法,特别是如果需要导入re来实现更复杂的模式,而不是简单的字符串

#! /usr/bin/env python3

pattern='some text'
f = open('input.txt', 'r')
g = open('output.txt', 'w')
l=f.readlines()
f.close()
for ind in range(len(l)):
    if pattern in l[ind]:
        l[ind+1]='#' + l[ind+1]
for field in l:
    g.write(field)
g.close()
print('Done')

sed的可能副本至少是可疑的。正确的将是sed-i'/pattern/{N;s/\N/\N}文件。任何python解决方案都会更长。感谢您的回答。作品因此,如果没有第二个临时工,就没有机会进行就地编辑。文件?不是真的,你可以在原地查看fileinput,但它仍然会创建一个临时备份文件,所以没有骰子。