Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed replace with variable with multiple lines [duplicate]

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?

like image 910
Andreas Avatar asked Jul 13 '11 19:07

Andreas


2 Answers

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"
like image 109
Toby Speight Avatar answered Sep 22 '22 13:09

Toby Speight


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.

like image 44
Diego Sevilla Avatar answered Sep 22 '22 13:09

Diego Sevilla