Sed and awk: how to replace file section with other content?

A.html file:

<!--TEMPLATE: banner--> blahblah <!--TEMPLATE-END: banner--> 

I want to replace the middle text with some other text, how to achieve this using sed / awk / other tools?

+6
awk sed
source share
3 answers

If you have new banner text in another file:

 awk -v new_file=new_banner.txt ' /!--TEMPLATE:/ {print; system("cat " new_file); banner=1; next} /!--TEMPLATE-END:/ {banner=0} banner {next} {print} ' a.html 
+2
source share

If the text between the marker lines consists of one or more lines:

 sed '/<!--TEMPLATE: banner-->/,/<!--TEMPLATE-END: banner-->/ {//!d}; /<!--TEMPLATE: banner-->/aSome text to insert' a.html 

The i command can be changed to the r command and the file name to read text from the file.

 sed '/<!--TEMPLATE: banner-->/,/<!--TEMPLATE-END: banner-->/ {//!d}; /<!--TEMPLATE: banner-->/r filename' a.html 
+4
source share
 sed -r 'N;s/(<!--TEMPLATE: banner-->\n).*/\1lalala/' 

Enter

 $ cat sedbanner <!--TEMPLATE: banner--> blahblah <!--TEMPLATE-END: banner--> 

Exit

 $ sed -r 'N;s/(<!--TEMPLATE: banner-->\n).*/\1lalala/' ./sedbanner <!--TEMPLATE: banner--> lalala <!--TEMPLATE-END: banner--> 

If you like the output, replace sed -r with sed -ri to make it in-place editing

+1
source share

All Articles