Issue
I have a text file 1.txt
which has following content:
module abc
I am trying to generate multi-line string that I need to add before module abc
line in 1.txt
. I am using sed
to do this.
>>> match = ['a_defs', 'b_defs', 'c_defs']
>>> inc_str = ("\n").join(['`include "%s.vh"' % str for str in match])
>>> print("include string: ", inc_str)
include string: `include "a_defs.vh"
`include "b_defs.vh"
`include "c_defs.vh"
This is the sed
command I am forming and printing before executing it:
>>> print("sed -i '/module abc/i %s' 1.txt" % inc_str)
sed -i '/module abc/i '`include "a_defs.vh"\n`include "b_defs.vh"\n`include "c_defs.vh"'' 1.txt
When I execute the above sed
command, I get error:
> sed -i '/module abc/i '`include "a_defs.vh"\n`include "b_defs.vh"\n`include "c_defs.vh"'' 1.txt
Unmatched `.
There shouldn't be '
before and after the string that gets substituted in the sed
command, but not sure how to get rid of them.
This behavior is with Python3.10
.
This works fine:
sed -i '/module abc/i `include "a_defs.vh"\n`include "b_defs.vh"\n`include "c_defs.vh"' 1.txt
This is the behavior in Python2.7
:
> python2
Python 2.7.5 (default, Nov 16 2020, 22:23:17)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> match = ['a_defs', 'b_defs', 'c_defs']
>>> inc_str = ("\n").join(['`include "%s.vh"' % str for str in match])
>>> print("sed -i '/module abc/i %s' 1.txt" % inc_str)
sed -i '/module abc/i `include "a_defs.vh"
`include "b_defs.vh"
`include "c_defs.vh"' 1.txt
I tried repr
, strip
, but didn't help. Can someone please help me resolving this?
Solution
If you want to convert newlines to \n characters (which means 'newline' to sed) just substitute them using following statement:
>>> print("sed -i '/module abc/i %s' 1.txt" % inc_str.replace('\n', '\\n'))
sed -i '/module abc/i `include "a_defs.vh"\n`include "b_defs.vh"\n`include "c_defs.vh"' 1.txt
Answered By - nsilent22 Answer Checked By - Terry (WPSolving Volunteer)