Ross
Ross

Reputation: 829

linux sed how to wrap a multiline search pattern with text

I have a html file which includes a section as follows:

<div id='webnews'>
... variable stuff ...
</div>

which I want to comment out as follows:

<!--
<div id='webnews'>
 ... variable stuff ...
</div>
-->

I can find & print the multiline text as follows:

sed '/<div id="webnews"/, /<\/div>/ { p }' filename.html

Experimenting with h, d, x and G, I have been unable work out how to either wrap the hold buffer or the pattern buffer with '<!--' and '-->'.

Would appreciate help with this challenge.

Upvotes: 1

Views: 285

Answers (3)

Louis Kottmann
Louis Kottmann

Reputation: 16618

Sed is not the right tool for the job.

Use sift:

sift -m '(.+)(<div id=.webnews.>.*</div>)(.+)' --replace '$1<!-- $2 -->$3'

Upvotes: 1

potong
potong

Reputation: 58371

This might work for you (GNU sed):

sed -e '/<div id='\''webnews'\''>/,/<\/dev>/!b;/<div id='\''webnews'\''>/i\<!--' -e '/<\/div>/a\-->' file

Or perhaps:

sed $'/<div id=.webnews.>/,/<\/dev>/{/<div id=.webnews.>/i\<!--\n;/<\/div>/a\-->\n}' file

Upvotes: 1

NeronLeVelu
NeronLeVelu

Reputation: 10039

quick and dirty with sed (not the best idea on html unless you are sure of html content/structure)

sed "/<div id='webnews'/, /<\/div>/ {
  /<div id='webnews'/ { 
     h
     d
     }
  H 
  /<\/div>/ !d
  x
  s/^/<!--\\
/
  s/$/\\
-->/
  }" filename.html

Upvotes: 1

Related Questions