I'm working on a bash-script that has to prepare an E-Mail for being sent to a user.
It aggregates some data, which ends up being multiple lines of stuff. For the example stored in $DATA
.
Now, after a bit of stfw I found a few things like sed -ei "s/_data_/${DATA}/g" mail.tpl
and also sed replace with variable with multiple lines. None of them work.
Now the question is, how do I get sed
to replace something with multiple lines of text?
(Alternatives to sed
are also welcome!)
awk?
I tried it and
sed 's/pattern/\na\nb\nc/g'
but it does not work on all systems. What does work is putting a\
followed by a newline in the replace pattern, like this:This appends a line containing
b
and a line containingc
when the pattern is seen.To put it in a variable, use double backslashes:
and then:
Note the double quotes.
ring bearer's answer didn't work for me; I think the usage of
tr
there is wrong, and the way it's written, it simply strips away newlines by use ofecho
.Instead, I used
sed
. I used code from another answer to replace newlines (credit: Zsolt Botykai). I also expected some dollar signs ($
) in my input so I took care of that too. You might need to add other input handling. Note the use of double quotes inecho
to preserve newlines.Then you can use
${ESCAPED_DATA}
insed
:Just thought I'd share.
If you build your multiple line text with "
\n
"s, this will work with a simplesed
command as:I would suggest simply replacing sed with perl command like this:
Escaping all the newlines with a
\
(except the last one) worked for me. The last newline must not be escaped not to break thes
command.Example :