I'm trying to replace a single line in a file with a multiline string stored in a variable.
I am able to get the correct result when printing to screen, but not if I want to do an in-place replacement.
The file has form:
*some code*
*some code*
string_to_replace
*some code*
I want the resulting file to be:
*some code*
*some code*
line number 1
line number 2
line number 3
*some code*
The code I tried was:
new_string="line number 1\nline number 2\nline number 3"
# Correct output on screen
sed -e s/"string_to_replace"/"${new_string}"/g $file
# Single-line output in file: "line number 1line number 2line number 3"
sed -i s/"string_to_replace"/"${new_string}"/g $file
When trying to combine -i
and -e
options, the result is the same as when only using -i
.
I'm using GNU sed version 4.1.5 on CentOS (connected to it through ssh from Mac).
In sed
you can double quote the command string and let the shell do the expansion for you, like this:
new_string="line number 1\nline number 2\nline number 3"
sed -i "s/string_to_replace/$new_string/" file