new.txt works fine in bash terminal But below python code doesnot execute :- file1=ol" /> new.txt works fine in bash terminal But below python code doesnot execute :- file1=ol" /> new.txt works fine in bash terminal But below python code doesnot execute :- file1=ol"/>

Variable Substiution in sed executing via python

173 Views Asked by At

Below is my sed command:

sed "s/N([0-9]*)/sum('\1')/g" old.txt > new.txt

works fine in bash terminal

But below python code doesnot execute :-

file1=old.txt
file2.new.txt
sed_cmd = 'sed "s/0x\([0-9]*\)/sum('\1')/g" %s > %s' %(file1,file2)

I get syntax error

After above I need do :-

subprocess.call([sed_cmd],shell=True)
1

There are 1 best solutions below

0
Wiktor Stribiżew On

Main issues:

  • Single quotes ' are used unescaped in a regular single quoted string literal (that make the syntax corrupt)
  • \1 inside a regular string literal defines a \x01 character, a SOH char, and not a regex backreference (that requires two char combination, \ + here, 1).

You can use

sed_cmd = r"""sed "s/0x\([0-9]*\)/sum('\1')/g" {} > {}""".format(file1,file2)

Details:

  • r"""...""" is a triple-quoted raw string literal inside which you may freely use unescaped ' and ", and \ chars denote literal backslashes
  • {} are placeholders in the format string, the first one will be filled with the contents of the first and second variables passed as arguments in parentheses (see .format(file1,file2)).