我有一個1.txt包含以下內容的文本檔案:
module abc
我正在嘗試生成需要在module abcline in之前添加的多行字串1.txt。我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
我試過了repr,strip但沒有幫助。有人可以幫我解決這個問題嗎?
uj5u.com熱心網友回復:
如果要將換行符轉換為 \n 字符(這意味著 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/462385.html
標籤:Python python-3.x 细绳 重击 sed
