Sed Multi-line Replace – How to Perform Multi-line Replace

sed

I spent ages trying to figure this out. As it happens, I don't need to do it any more; I found another way. But for the sake of my sanity, I'd like to know the answer anyway.

It's quite easy to use sed to replace a marker with some piece of text. What I can't figure out is how to make sed insert a huge block of text, with complex formatting such as multiple lines, tab characters, etc. How do you do that? Is sed the best thing to use or what?

Best Answer

If you have the text to be inserted at the marker(s) in a file named /tmp/insert.txt you can accomplish this task as follow:

sed '/MARKER/ r /tmp/insert.txt' < inputfile

The above sed command will read "inputfile" and look for MARKER. When it finds it, it inserts the contents of /tmp/insert.txt into the output stream.

If you want the marker itself to be deleted, try this:

sed '/MARKER/ {s/MARKER//; r /tmp/insert.txt
}' <inputfile

Note the "}" closing brace must be preceded by a new line.

As in the first command, the sed will operate on lines with the MARKER. It will substitute MARKER with nothing, and then it will read in /tmp/insert.txt