Replace a word with multiple lines using sed? Replace a word with multiple lines using sed? bash bash

Replace a word with multiple lines using sed?


You can do this with AWK using variable substitution. We can set a variable in AWK using -v, and then use AWK's gsub function to substitute all occurrences of a regular expression with that variable.

For example, if the file test has the following contents ...

foobarblah _data_and_data_foo_data_ foobar _data_ again

... and the Bash variable $DATA is ...

12345

... then awk -v r=$DATA '{gsub(/_data_/,r)}1' test replaces all occurrences of the regular expression _data_ in the file test with the contents of $DATA, resulting in the following:

foobarblah 12345and12345foo12345 foobar 12345 again


If you build your multiple line text with "\n"s, this will work with a simple sed command as:

DATA=`echo ${DATA} | tr '\n' "\\n"`#now, DATA="line1\nline2\nline3"sed "s/_data_/${DATA}/" mail.tpl


I would suggest simply replacing sed with perl command like this:

perl -i.bak -pe 's/_data_/$ENV{"DATA"}/g' mail.tpl