[sed]: Substitute a string with a multiline value

Dear all,

I try to replace a string of characters in a file (MyFile.txt) by a multiline value of the variable "Myvar":

[x004191a@xsnl11p317a TEST_DAE]$ cat MyFile.txt
DESCRIPTION '@TargetTable SCHEMA'
(
 @InputFlowDef
);
[x004191a@xsnl11p317a TEST_DAE]$

The content of Myvar:

[x004191a@xsnl11p317a TEST_DAE]$ echo "$Myvar"
col1
, col2
, col3
[x004191a@xsnl11p317a TEST_DAE]$

Using sed command in the following way, I got the error:

[x004191a@xsnl11p317a TEST_DAE]$ sed "s/@InputFlowDef/$Myvar/" MyFile.txt
sed: -e expression #1, char 20: unterminated `s' command
[x004191a@xsnl11p317a TEST_DAE]$

My aim is to get the following result:

[x004191a@xsnl11p317a TEST_DAE]$ cat MyFileResult.txt
DESCRIPTION '@TargetTable SCHEMA'
(
col1
, col2
, col3
);
[x004191a@xsnl11p317a TEST_DAE]$

Any help would be greatly appreciated,

Didier.

while read line
do
   if [ "$line" = "@InputFlowDef" ]
   then
     echo "$Myvar"
   else
     echo "$line"
   fi
done < MyFile.txt
1 Like

I don't think you can do this with sed and a shell variable. Create a temp file and use that:

echo "$Myvar" >/tmp/XX
sed -e'/@InputFlowDef/ {r/tmp/XX' -e';d}' file
DESCRIPTION '@TargetTable SCHEMA'
(
col1
, col2
, col3
);

Or use e.g. awk ...

1 Like

rdrtx1 & RudiC, thanks a lot for your answers !

RudiC, you mentioned in your answer awk would be useful to carry out that kind of operation.

If you have few minutes, would you like to share the syntax ?

Using awk:-

awk -v S="$Myvar" '/@InputFlowDef/{$0=S}1' MyFile.txt
1 Like