Search code examples
bashtextsedreplacemacos-sierra

How do I use gsed on macOS to replace a string with the contents of a file?


I need to take a text file, an index.html specifically, and insert the contents of another text file into a specific spot in that text file, but not at the end of the line.

I understand how to replace (substitute) the text with a string, as follows:

gsed 's/WHAT_TO_SUBSTITUTE/WHAT_TO_SUBSTITUTE_WITH/' index.html > index-new.html

However when I try to substitute with the contents of a file, I run into issues. Here's what I've tried:

gsed 's/<!--New Posts Go Below This Line-->/r newpost.txt/' index.html > index-new.html

The above does not work at all.

gsed -s '/<!--New Posts Go Below This Line-->/ r newentry.txt' index.html > index-new.html

The above inserts the contents of the file, but at the end of the line instead of substituting the string (as expected)

Contents of text file:

<!--New Posts Go Below This Line--> <div class=panel panel-default><div class=panel-heading><h4 class=panel-title><a data-parent=#accordion data-toggle=collapse href=#collapse56> February 31st, 2069 - New Post </a></h4></div><div class=panel-collapse collapse  id=collapse56><div class=panel-body><img alt=my_favorite_image.png div= src=/render/file.act?path=/my_favorite_image.png /></div></div></div>

Expected output (keep in mind, because of my company's CMS, the html I'm working with is one large block once written to the web server):

....index.html_HTML_code....<!--New Posts Go Below This Line-->CONTENTS_OF_newpost.txt.....index.html_HTML_code....

Solution

  • To replace <!--New Posts Go Below This Line--> with content from newpost.html you could stick with simple shell command substitution:

    gsed "s/<!--New Posts Go Below This Line-->/$(cat newpost.txt)/" index.html > index-new.html
    

    Edit:

    This will only work, if newpost.txt does not contain newlines. Doing stuff with multiple lines with sed is very hard because the syntax is very obscure and hard to read.

    I strongly recommend another tool for the job. For example Perl:

    perl -pe 's/<!--New Posts Go Below This Line-->/`cat newpost.txt`/ge' index.html > index-new.html