Just thought I would post this tip - didn't find it very easily
anywhere.
When using shell variables on a multiple line sed statement, you need
to use double quotes and escape the backslash:
For example, if I am doing a search and replace on the file test.txt
containing the following lines:
#BEGIN
Text to be replaced
#END
other text
and would like to replace the lines starting with #BEGIN and ending
with #END with the text contained on $REPLACEMENT_TEXT, use this sed
command:
sed "/#BEGIN/,/#END/c\\
$REPLACEMENT_TEXT
" test.txt > newfile.txt
INSTEAD OF:
sed '/#BEGIN/,/#END/c\
$REPLACEMENT_TEXT
' test.txt > newfile.txt
(which will not expand $REPLACEMENT_TEXT)
Normally, you wouldn't use double quotes, but you need to in order to
expand the variable. Without escaping the backslash at the end of the
first line sed chokes.
This is with gnu sed and using bash shell. Don't know about others.