Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed and awk: how to replace a section of file to another content?

Tags:

sed

awk

File a.html:

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

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

like image 677
Bin Chen Avatar asked Nov 30 '10 08:11

Bin Chen


2 Answers

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 could be changed to an r command and a file name to read the text from a file.

sed '/<!--TEMPLATE: banner-->/,/<!--TEMPLATE-END: banner-->/ {//!d}; /<!--TEMPLATE: banner-->/r filename' a.html
like image 84
Dennis Williamson Avatar answered Sep 20 '22 03:09

Dennis Williamson


If you have the 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
like image 39
glenn jackman Avatar answered Sep 22 '22 03:09

glenn jackman