sed replace with variable with multiple lines [duplicate]

Given that you’re using Bash, you can use it to substitute \n for the newlines:

sed -e "s/TOREPLACE/${TEST//$'\n'/\\n}/" file.txt

To be properly robust, you’ll want to escape /, & and \, too:

TEST="${TEST//\\/\\\\}"
TEST="${TEST//\//\\/}"
TEST="${TEST//&/\\&}"
TEST="${TEST//$'\n'/\\n}"
sed -e "s/TOREPLACE/$TEST/" file.txt

If your match is for a whole line and you’re using GNU sed, then it might be easier to use its r command instead:

sed -e $'/TOREPLACE/{;z;r/dev/stdin\n}' file.txt <<<"$TEST"

Leave a Comment