开发者

Are there any ways in Bash to insert a paragraph before the matched pattern?

开发者 https://www.devze.com 2023-03-21 10:55 出处:网络
Sorry but I am still stuck on this problem. I would like to insert a paragraph before the first match of \"<tr><td nowrap valign=\"top\"/paragraph\"

Sorry but I am still stuck on this problem. I would like to insert a paragraph before the first match of "<tr> <td nowrap valign="top"/paragraph"

So I use this code:

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

However, the program returns me the whole page of that HTML file and no insertion happens.

Also, I would like to insert some values in the variable in sed code; can I do that?

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


To insert before a pattern, you have to make sure your pattern matches something in the file.

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>

The "*" above matches any amount of spaces. Maybe that is what's causing your command to fail. Of course you need the "-i" switch if you want to edit the file in-place.

For the second question, sed -i 's/old/$new/g' file, that is almost right except you need to use double-quotes (") instead of single-quotes (') in order for string interpolation to work: sed -i "s/old/$new/g" file

See http://www.linuxtopia.org/online_books/linux_tool_guides/the_sed_faq/sedfaq4_004.html from How to use sed to replace only the first occurrence in a file? for syntax on replacing only the first match.

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号