在 Python 中的 sed 命令中删除替换字符串中的单引号

Get rid of single quotes from the substituted string within sed command in Python

我有一个文本文件 1.txt,其中包含以下内容:

module abc

我正在尝试生成需要在 1.txt 中的 module abc 行之前添加的多行字符串。我正在使用 sed 来执行此操作。

>>> 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"

这是我在执行前形成并打印的sed命令:

>>> 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

当我执行上面的sed命令时,出现错误:

> sed -i '/module abc/i '`include "a_defs.vh"\n`include "b_defs.vh"\n`include "c_defs.vh"'' 1.txt
Unmatched `.

sed 命令中被替换的字符串前后不应该有 ',但不知道如何去掉它们。 这种行为是 Python3.10.

这很好用:

sed -i '/module abc/i `include "a_defs.vh"\n`include "b_defs.vh"\n`include "c_defs.vh"' 1.txt

这是 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

我尝试了 reprstrip,但没有帮助。有人可以帮我解决这个问题吗?

如果你想将换行符转换为 \n 字符(这意味着 'newline' 到 sed)只需使用以下语句替换它们:

>>> 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