subprocess.call with sed pass variable

时间:2016-10-18 08:02:52

标签: python sed subprocess

我正在尝试使用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

1 个答案:

答案 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'

参考:Python: Prevent fileinput from adding newline characters