cyrilPA
cyrilPA

Reputation: 269

Search and replace $ signs with sed

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

Answers (4)

Ed Morton
Ed Morton

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

user1006989
user1006989

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

anubhava
anubhava

Reputation: 785266

You can use:

sed 's/\$\$placeholder\$\$/'"$o"'/g'

Upvotes: 1

Pilou
Pilou

Reputation: 1478

You can add simple quotes around $o :

sed -i "" -e 's/\$\$placeholder\$\$/'$o'/g' test.txt

Upvotes: 0

Related Questions