Reputation: 8384
If I want to replace for example the placeholder {{VALUE}}
with another string which can contain any characters, what's the best way to do it?
Using sed s/{{VALUE}}/$(value)/g
might fail if $(value)
contains a slash...
Upvotes: 1
Views: 848
Reputation: 8711
The question asked basically duplicates How can I escape forward slashes in a user input variable in bash?, Escape a string for sed search pattern, Using sed in a makefile; how to escape variables?, Use slashes in sed replace, and many other questions. “Use a different delimiter” is the usual answer. Pianosaurus's answer and Ben Blank's answer list characters (backslash and ampersand) that need to be escaped in the shell, besides whatever character is used as an alternate delimiter. However, they don't address the quoting-a-quote problem that will occur if your “string which can contain any characters” contains a double quote. The same kind of problem can affect the ${parameter/pattern/string}
shell variable expansion mentioned in a previous answer.
Some other questions besides the few mentioned above suggest using awk, and that is usually a good approach to changes that are more complicated than are easy to do with sed. Also consider perl and python. Besides single- and double-quoted strings, python has u'...'
unicode quoting, r'...'
raw quoting,ur'...'
quoting, and triple quoting with '''
or """
delimiters. The question as stated doesn't provide enough context for specific awk/perl/python solutions.
Upvotes: 0
Reputation: 19335
oldValue='{{VALUE}}'
newValue='new/value'
echo "${var//$oldValue/$newValue}"
but oldValue is not a regexp but works like a glob pattern, otherwise :
echo "$var" | sed 's/{{VALUE}}/'"${newValue//\//\/}"'/g'
Upvotes: 3
Reputation: 5772
Sed also works like 's|something|someotherthing|g'
(or with other delimiters for that matter), but if you can't control the input string, you'll have to use some function to escape it before passing it to sed..
Upvotes: 0