Thursday, October 28, 2021

[SOLVED] Prepend file content to match in sed

Issue

I am trying to append the content of a file before the closing body tag in an html document. I've tried

cat test.html | sed  -e $'/<\/body>/{ r insert.html ... }'

using various combinations of \np, \nd at ..., but everything seems to be inserted after the tag.

It would also be nice if additional string constants could be added around the content of insert.html, such as centering tags etc.


Solution

If sed is your hard requirement, you can try this in GNU sed:

sed '/<\/body>/e cat insert.html' test.html

It uses GNU-specific e shell-command (e cat filename here), which will, unlike r filename be executed before the end of the current cycle (before </body> line is processed/printed).


Note (from the docs) r filename will:

Queue the contents of filename to be read and inserted into the output stream at the end of the current cycle, or when the next input line is read.

and e command:

[...] unlike the r command, the output of the command will be printed immediately; the r command instead delays the output to the end of the current cycle.



Answered By - randomir