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

╄→尐↘猪︶ㄣ 提交于 2019-12-11 14:13:54

问题


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'

回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/46894339/replacing-string-with-variable-in-bash-when-variable-starts-with-special-charact

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!