Using GNU sed
.
mline="this is\na line\nin multiple\nlines"
sed "s/PATTERN/${mline}/g" <<<"PATTERN here."
this is
a line
in multiple
lines here.
If your input contains /
as special character or &
which will match as pattern match in sed
. Use global Pattern Substitution //
to replace/escape all /
es and replace back all PATTERNs with \&
.
sed "s/PATTERN/${mline//\//\\/}/g; s/PATTERN/\&/" <<<"PATTERN here."
Or either better to use different sed
's substation delimiter and escape &
again.
sed "s:PATTERN:${mline//&/\\&}:g" <<<"PATTERN here."
And finally if you want it works on actual Enter, first we need to replace all \n
with \\n
to let them feed to sed as \n
. So
Input in multiple lines with actual enter.
mline="th&is is
a line
in mul/tiple
line/s"
The command:
aline="$(sed -z 's:\n:\\n:g;$s:\\n$::' <<<"$mline")
sed "s:PATTERN:${aline//&/\\&}:g" <<<"PATTERN here."
The output is:
th&is is
a line
in mul/tiple
line/s here.
sed
as the delimiter for the substitution command need to use a character that is guaranteed to not occur in the pattern nor replacement. One would need to pre-process the string first. – Kusalananda Oct 04 '17 at 19:37