string Shell 脚本变量替换字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5833086/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:04:45  来源:igfitidea点击:

Shell script variable replacing characters

shellvariablesstring

提问by thetux4

I have a variable var="abcde$$$$$$$$fff$$gg". I want to replace all $ with space ' ' but the following puts just one space

我有一个变量 var="abcde$$$$$$$$fff$$gg"。我想用空格 ' ' 替换所有 $ 但下面只放一个空格

var=$( echo "$var" | tr '$' ' ')

How can i replace them all?

我怎样才能全部替换它们?

回答by ghostdog74

you can replace without calling external commands (using bash)

您可以在不调用外部命令的情况下进行替换(使用 bash)

$ var='abcde$$$$$$$$fff$$gg'
$ echo "${var//$/ }"
abcde        fff  gg

Note that you should use single quotes so that the "$" sign does not get interpolated

请注意,您应该使用单引号,以便“$”符号不会被插入

回答by l0b0

Works for me. You'll need to use single quotes or escape the dollar signs, otherwise they are removed from the double-quoted string:

对我来说有效。您需要使用单引号或转义美元符号,否则它们将从双引号字符串中删除:

echo 'abcde$$$$$$$$fff$$gg' | tr '$' ' '
abcde        fff  gg

echo "abcde$$$$$$$$fff$$gg" | tr '$' ' '
abcde        fff  gg

echo abcde$$$$$$$$fff$$gg | tr '$' ' '
abcde        fff  gg

echo $'abcde$$$$$$$$fff$$gg' | tr '$' ' '
abcde        fff  gg

回答by Swepter

Old question, but I write this for them hwo will come here after a search with their diseired search engine You have to use echo -elike this

老问题,但我写这为他们与他们的diseired搜索引擎搜索后藿会来这里,你必须使用echo -e类似这样的

var="$( echo -e "$var" | tr  '$' ' '  )"