Reputation: 1783
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'
Upvotes: 0
Views: 95
Reputation: 241741
For this particular use case, there is no need to use sed
, and the native bash solution is simpler, more efficient, and less fiddly (because you don't need to worry about delimiters or other special characters in the replacement string):
$ for s in ./3 ./2 ./1; do echo "${astring/\[sec\]/$s}"; done
Liftoff in ./3
Liftoff in ./2
Liftoff in ./1
See the list of bash parameter expansion syntaxes in the Bash manual.
Upvotes: 0
Reputation: 185171
You just have to use another delimiter :
for s in ./3 ./2 ./1; do echo "$s" | sed -e "s|\[sec\]|$s|"; done
to avoid conflict with your input
Upvotes: 1