[英]Python search string and replace character in next line
in a text file I want to search for a line containing specific text and at the next line I want to substitute beginning of a line with #(comment it out) inplace: 在文本文件中,我要搜索包含特定文本的行,在下一行中,我要在行的开头替换为#(注释掉):
Example - before: 示例-之前:
#test search 123
text to be commented out
#test 123
Example - wanted: 示例-想要:
#test search 123
#text to be commented out
#test 123
I can do it via sed: 我可以通过sed来做到这一点:
sed -i '/^#test search 123/!b; n; s/^/#/' test_file
but i was wondering if I'm able to do it natively in python. 但我想知道我是否能够在python中本地执行此操作。
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')
Correct sed will be 正确的sed将是
sed -i '/pattern/ {N; s/\n/\n#/}' file
This which follows maybe is not most pythonic way of same, specially if import re is needed for more complicated pattern then simple string 这可能不是大多数的pythonic方式,特别是如果需要import 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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.