Home:ALL Converter>Replacing string with variable in bash when variable starts with special characters

Replacing string with variable in bash when variable starts with special characters

Ask Time:2017-10-24T00:37:26         Author:Michael Gruenstaeudl

Json Formatter

Replacing a string with the contents of a variable using sed by enclosing the search expression with double (") instead of single (') quotes is well documented.

$ astring="Liftoff in [sec]"
$ for s in 3 2 1; do echo $astring | sed -e "s/\[sec\]/$s/"; done
Liftoff in 3
Liftoff in 2
Liftoff in 1

However, how do I conduct the above replacement if the variable content starts with special characters? For example, the variable contents could start with a period forwardslash (./), which is often the case if local file paths are passed as variables?

for s in ./3 ./2 ./1; do echo $astring | sed -e "s/\[sec\]/$s/"; done
sed: -e expression #1, char 14: unknown option to `s'
sed: -e expression #1, char 14: unknown option to `s'
sed: -e expression #1, char 14: unknown option to `s'

Author:Michael Gruenstaeudl,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/46894339/replacing-string-with-variable-in-bash-when-variable-starts-with-special-charact
Gilles Quénot :

You just have to use another delimiter : \n\nfor s in ./3 ./2 ./1; do echo \"$s\" | sed -e \"s|\\[sec\\]|$s|\"; done\n\n\nto avoid conflict with your input",
2017-10-23T16:40:09
yy