I'd like to insert multiple lines above a target line in a file by using sed.
The file.txt
below contains one line "target line
". My initial version is using the single quote:
sed '/target line/ i\
inserted line1;\
inserted line2;\
inserted line3;' file.txt
The result is:
inserted line1;
inserted line2;
inserted line3;
target line
This version works as expected that the newline at the end of each line is escaped by \
to a literal newline instead of a command terminator. Refer to here.
Then I'd like to use shell variable in the replacement string, so I tried to use double quotes to enable the variable expansion:
sed "/target line/ i\
inserted line1;\
inserted line2;\
inserted line3;" file.txt
But this time the newline and the first four spaces disappeared:
inserted line1; inserted line2; inserted line3;
target line
How do I correctly insert a newline in double quotes here?