我正在尝试使用subprocess.call
运行Python脚本以在匹配模式后添加一行。这是方法:
addline1
是变量,其值为"hello world1"
filename1
是包含例如"/tmp/path1/filename.conf"
在filename.conf
中,它有~35行,我想在匹配字符串"ReWriteEngine On"
之后插入一行
subprocess.call(["sed","-i" ,'/ReWriteEngine On/a', addline1,filename])
并且失败并出现以下异常:
**sed: -e expression #1, char 16: expected \ after `a', `c' or `i'**
任何人都可以建议进行任何更正吗?
代码尝试使用fileinput
代替sed
import fileinput
processing_foo1s = False
for line in fileinput.input('/tmp/filename1/mod_wl_ohs.conf', inplace=1):
if line.startswith("RewriteEngine On"):
processing_foo1s = True
else:
if processing_foo1s:
print 'foo bar'
processing_foo1s = False
print line
答案 0 :(得分:0)
更正sed
问题:
sed_cmd = '/ReWriteEngine On/a' + addline1
subprocess.call(['sed', '-i', sed_cmd, filename1])
注意:如果字符串必须在行首处匹配,请使用/^ReWriteEngine On/a
使用fileinput
:
import fileinput
for line in fileinput.input(filename1, inplace=1):
print line,
if line.startswith("ReWriteEngine On"):
print 'foo bar'