bash 如何使用shell按字符替换特殊字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15278793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to replace a special characters by character using shell
提问by gmhk
I have a string variable x=tmp/variable/custom-sqr-sample/test/examplein the script, what I want to do is to replace all the “-” with the /,
after that,I should get the following string
我x=tmp/variable/custom-sqr-sample/test/example在脚本中有一个字符串变量,我想要做的是用/替换所有的“-”,之后,我应该得到以下字符串
x=tmp/variable/custom/sqr/sample/test/example
Can anyone help me?
谁能帮我?
I tried the following syntax it didnot work
我尝试了以下语法它不起作用
exa=tmp/variable/custom-sqr-sample/test/example
exa=$(echo $exa|sed 's/-///g')
回答by Fredrik Pihl
sed basically supports any delimiter, which comes in handy when one tries to match a /, most common are |, #and @, pick one that's not in the string you need to work on.
sed 基本上支持任何定界符,当您尝试匹配 a 时,它会派上用场/,最常见的是|,#和@,选择一个不在您需要处理的字符串中的定界符。
$ echo $x
tmp/variable/custom-sqr-sample/test/example
$ sed 's#-#/#g' <<< $x
tmp/variable/custom/sqr/sample/test/example
In the commend you tried above, all you need is to escape the slash, i.e.
在你上面试过的推荐中,你所需要的就是逃避斜线,即
echo $exa | sed 's/-/\//g'
but choosing a different delimiter is nicer.
但选择不同的分隔符更好。
回答by danfuzz
The trtool may be a better choice than sedin this case:
该tr工具可能是比sed这种情况更好的选择:
x=tmp/variable/custom-sqr-sample/test/example
echo "$x" | tr -- - /
(The --isn't strictly necessary, but keeps tr(and humans) from mistaking -for an option.)
(这--不是绝对必要的,但可以防止tr(和人类)误认为-一个选项。)
回答by chepner
In bash, you can use parameter substitution:
在 中bash,您可以使用参数替换:
$ exa=tmp/variable/custom-sqr-sample/test/example
$ exa=${exa//-/\/}
$ echo $exa
tmp/variable/custom/sqr/sample/test/example

