I am trying to replace a word with a text which spans multiple lines. I know that I can simply use the newline character \n to solve this problem, but I want to keep the string "clean" of any unwanted formatting.
The below example obviously does not work:
read -r -d '' TEST <<EOI
a
b
c
EOI
sed -e "s/TOREPLACE/${TEST}/" file.txt
Any ideas of how to achieve this WITHOUT modifying the part which starts with read and ends with EOI?
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"
You can just write the script as follows:
sed -e 's/TOREPLACE/a\
b\
c\
/g' file.txt
A little cryptic, but it works. Note also that the file won't be modified in place unless you use the -i
option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With