subprocess.call with sed pass variable
<p>I am trying to run Python script with <code>subprocess.call</code> to add a line after matching pattern. Here's the ways :</p>

<p><code>addline1</code> is variable and has the value say <code>"hello world1"</code></p>

<p><code>filename1</code> is the variable containing path and file name for example <code>"/tmp/path1/filename.conf"</code></p>

<p>in the <code>filename.conf</code>, it has ~35 lines and i wanted to insert one line after matching string <code>"ReWriteEngine On"</code></p>

<pre><code>subprocess.call(["sed","-i" ,'/ReWriteEngine On/a', addline1,filename])
</code></pre>

<p>and it fails with below exception:</p>

<pre><code>**sed: -e expression #1, char 16: expected \ after `a', `c' or `i'**
</code></pre>

<p>Can any one please advice any correction to be made ?</p>

<p><br>
Code tried with <code>fileinput</code> instead of <code>sed</code></p>

<pre><code>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
</code></pre>

<p>Correcting the <code>sed</code> issue:</p>

<pre><code>sed_cmd = '/ReWriteEngine On/a' + addline1
subprocess.call(['sed', '-i', sed_cmd, filename1])
</code></pre>

<p><strong>Note:</strong> Use <code>/^ReWriteEngine On/a</code> if the string has to match at start of line</p>

<p><br>
With <code>fileinput</code>:</p>

<pre><code>import fileinput
for line in fileinput.input(filename1, inplace=1):
    print line,
    if line.startswith("ReWriteEngine On"):
        print 'foo bar'
</code></pre>

<p>Reference: <a href="http://stackoverflow.com/questions/657186/python-prevent-fileinput-from-adding-newline-characters">Python: Prevent fileinput from adding newline characters</a></p>

python sed subprocess