Reputation: 269
I would like to use sed to replace in files placeholders written like this $$placeholder$$ with the content of a variable.
Is it even possible ?
This is what I tried:
sed -i "" -e 's/\$\$placeholder\$\$/$o/g' test.txt
Half working, replace $$placeholder$$ by $o instead of the content of the $o variable
sed -i "" -e "s/\$\$placeholder\$\$/$o/g" test.txt
Not matching any of the $$placeholder$$ in my text
Thanks by advance.
Cyril
Upvotes: 3
Views: 1252
Reputation: 203674
sed is a fine tool for simple replacements on a single line, but for anything else (including using a variable in the substitution) just use awk:
$ cat file
foo $$placeholder$$ bar
$ o="hello
world"
$ sed 's/\$\$placeholder\$\$/'"$o"'/g' file
sed: -e expression #1, char 27: unterminated `s' command
$ awk -v o="$o" '{gsub(/\$\$placeholder\$\$/,o)}1' file
foo hello
world bar
That way you don't need to worry about any characters sed considers "special" or mess around with jumping back and for the between sed and shell on your command line by carefully quoting sections of your script.
Upvotes: 0
Reputation:
double escape the dollar:
sed -i "s/\\$\\$placeholder\\$\\$/$o/g" test.txt
in case your variable contains your delimiter, you might do some string substitution on it first:
sed -i "s/\\$\\$placeholder\\$\\$/${o//\//\\/}/g" test.txt
Upvotes: 1
Reputation: 1478
You can add simple quotes around $o
:
sed -i "" -e 's/\$\$placeholder\$\$/'$o'/g' test.txt
Upvotes: 0