Bash中是否有任何方法可以在匹配模式之前插入一个段落?

时间:2011-07-19 04:16:41

标签: bash

抱歉,我仍然坚持这个问题。 我想在"<tr> <td nowrap valign="top"/paragraph"

的第一场比赛之前插入一个段落

所以我使用这段代码:

sed '0,/<tr>                                  <td nowrap valign="top"/ { s/<tr>                                  <td nowrap valign="top"/paragraph\nsd/g }' /var/www/html/INFOSEC/english/news/test.html

但是,程序会返回该HTML文件的整个页面,不会发生插入。

另外,我想在sed代码中的变量中插入一些值;我能这样做吗?

eg. sed -i 's/old/$new/g' file

1 个答案:

答案 0 :(得分:4)

要在模式之前插入,您必须确保模式与文件中的某些内容匹配。

jcomeau@intrepid:/usr/src/clusterFix$ cat test.html
<tr> <td nowrap valign="top">blather blather blather</td></tr>
jcomeau@intrepid:/usr/src/clusterFix$ sed  '/<tr> *<td nowrap valign="top"/i<p>this is a new paragraph</p>' test.html
<p>this is a new paragraph</p>
<tr> <td nowrap valign="top">blather blather blather</td></tr>

上面的“*”匹配任意数量的空格。也许这就是导致你的命令失败的原因。当然,如果要在适当的位置编辑文件,则需要“-i”开关。

对于第二个问题,sed -i 's/old/$new/g' file,这几乎是正确的,除了您需要使用双引号(")而不是单引号(')才能进行字符串插值工作:sed -i "s/old/$new/g" file

有关仅替换第一场比赛的语法,请参阅http://www.linuxtopia.org/online_books/linux_tool_guides/the_sed_faq/sedfaq4_004.htmlHow to use sed to replace only the first occurrence in a file?

jcomeau@intrepid:/tmp$ cat test.txt 
this is not the test
this is not the test
this is a test
this is a test
this is a test
this is a test
this is a test
this is a test
jcomeau@intrepid:/tmp$ sed '0,/\(this is a test\)/s//before first match\n\1/' test.txt
this is not the test
this is not the test
before first match
this is a test
this is a test
this is a test
this is a test
this is a test
this is a test