sed to replace a line with multi lines from a var

I am trying to find a line in a file ("Replace_Flag") and replace it with a variable which hold a multi lined file.

myVar=`cat myfile`
sed -e 's/Replace_Flag/'$myVar'/' /pathto/test.file

myfile:
cat
dog
boy
girl
mouse
house

test.file:
football
hockey
Replace_Flag
baseball

What I'd like to see is:
football
hockey
cat
dog
boy
girl
mouse
house
baseball

The above command works if "myVar" is a signal line. example:

 myVar="this is a line"

or a line with the new line deliminators

 myVar="line1\nline2\nline3"

I also tried reformating the variable.

 myNEWVar=`cat $myVar | tr '\n' ' '` 

thus making it look like this: cat dog boy girl mouse house
however that did not work either.

any thoughts or suggestions would be greatly appreciated, thanks

Variables not in double quotes will split. Put it in double quotes to stop it splitting.

myVar="`cat myfile`"
sed -e 's/Replace_Flag/'"$myVar"'/' /pathto/test.file
 
sed '/Replace_Flag/r myfile' /pathto/test.file | sed '/Replace_Flag/d'
2 Likes

That's a much better solution than the original approach which is vulnerable to delimiters, backslash escape sequences, and ampersands in the replacement text. However, it suffers its own shortcoming: If the flag occurs in the replacement text, some (if not all) of the replacement text will be deleted.

Granted, that scenario is likely to be uncommon and it wasn't mentioned in the original problem statement, but since the fix is painless and also makes the solution more efficient, it seems like a good idea.

sed '/^FLAG$/{r myfile
d;}' /pathto/test.file

Regards,
Alister

1 Like

This works perfectly for what I am doing.

Thank you everyone for the suggestions! :slight_smile: