如何让 sed 替换第一次出现的以多字符定界符结尾的复杂字符串?
How do I get sed to substitute the first occurance of a complex string ending in a multi character delimiter?
我有一长行文本和 html 标签。我希望使用 sed 将字符串之间的字符替换为值 'MYSTART' 直到 </p>
在起始字符串之后第一次出现。替换文本是 RESULTSAFTERSUBSTITUTIONWORKS
我一直在摸索着正则表达式,一直碰壁。我还尝试了一些正则表达式测试站点,但无论是否使用“-r”,它们报告为成功的内容在 sed 中对我都不起作用。
cat myfile | sed -r 's/MYSTART.*?<\/p>/RESULTAFTERSUBSTITUTIONWORKS/'
我的示例字符串如下所示:
THISSHOULDBEIGNORED_MYSTART<ac>blah</ac><another>lots of things 123 abc :</another></p><div><ac>another thing</another><p>welcome home to somewhere</p></div>the line keeps going and going</p><p>paragraph</p>
替换后看起来像这样:
THISSHOULDBEIGNORED_RESULTAFTERSUBSTITUTIONWORKS<div><ac>another thing</another><p>welcome home to somewhere</p></div>the line keeps going and going</p><p>paragraph</p>
对于任何将 \n
识别为含义 <newline>
的 sed:
$ sed 's:</p>:\n:; s/MYSTART.*\n/RESULTAFTERSUBSTITUTIONWORKS/' file
THISSHOULDBEIGNORED_RESULTAFTERSUBSTITUTIONWORKS<div><ac>another thing</another><p>welcome home to somewhere</p></div>the line keeps going and going</p><p>paragraph</p>
如果您可以在开始字符串之前添加 </p>
s,那么它会更像这样(未经测试):
sed 's:</p>:\n:g; s/MYSTART[^\n]*\n/RESULTAFTERSUBSTITUTIONWORKS/; s:\n:</p>:g'
我有一长行文本和 html 标签。我希望使用 sed 将字符串之间的字符替换为值 'MYSTART' 直到 </p>
在起始字符串之后第一次出现。替换文本是 RESULTSAFTERSUBSTITUTIONWORKS
我一直在摸索着正则表达式,一直碰壁。我还尝试了一些正则表达式测试站点,但无论是否使用“-r”,它们报告为成功的内容在 sed 中对我都不起作用。
cat myfile | sed -r 's/MYSTART.*?<\/p>/RESULTAFTERSUBSTITUTIONWORKS/'
我的示例字符串如下所示:
THISSHOULDBEIGNORED_MYSTART<ac>blah</ac><another>lots of things 123 abc :</another></p><div><ac>another thing</another><p>welcome home to somewhere</p></div>the line keeps going and going</p><p>paragraph</p>
替换后看起来像这样:
THISSHOULDBEIGNORED_RESULTAFTERSUBSTITUTIONWORKS<div><ac>another thing</another><p>welcome home to somewhere</p></div>the line keeps going and going</p><p>paragraph</p>
对于任何将 \n
识别为含义 <newline>
的 sed:
$ sed 's:</p>:\n:; s/MYSTART.*\n/RESULTAFTERSUBSTITUTIONWORKS/' file
THISSHOULDBEIGNORED_RESULTAFTERSUBSTITUTIONWORKS<div><ac>another thing</another><p>welcome home to somewhere</p></div>the line keeps going and going</p><p>paragraph</p>
如果您可以在开始字符串之前添加 </p>
s,那么它会更像这样(未经测试):
sed 's:</p>:\n:g; s/MYSTART[^\n]*\n/RESULTAFTERSUBSTITUTIONWORKS/; s:\n:</p>:g'