Search code examples
bashsed

Replacing a string with a variable which contains newlines


I would like to replace a string with the a variable which contains newlines in it. However, sed replacing doesn't seem to do what I want.

  1. What I am doing now
    str=""
    str+="#My header 1"$'\n'
    str+="#My header 2"$'\n'
    str+="#My header 3"$'\n'

    echo "$str"

    #My header 1
    #My header 2
    #My header 3
    
    sed "s/##HEADER##/${str}/g" myfile.out

Unfortunately this does not work obtaining the following error:

sed: -e expression #1, char 25: unterminated s command

Any other ideas?


Solution

  • You need to escape back-slashes by repeating them:

    \\n