bash 用 sed 替换美元符号

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

Replace dollar sign with sed

linuxbashsed

提问by Severin

I try to replace all dollar signs in a string using sed. However, not only the dollar sign gets replaced but the whole string that follows.

我尝试使用 sed 替换字符串中的所有美元符号。然而,不仅美元符号被替换,而且后面的整个字符串也被替换。

$ echo "abc $def ghi" | sed 's/$//g'
$ abc ghi

$ echo "abc $def ghi" | sed 's/$//g'
$ abc ghi

If at least one number is following the dollar sign only the part before the first non-number gets replaced:

如果美元符号后面至少有一个数字,则仅替换第一个非数字之前的部分:

$ echo "abc $123def ghi" | sed 's/$//g'
$ abc def ghi

$ echo "abc $123def ghi" | sed 's/$//g'
$ abc def ghi

What is going on?

到底是怎么回事?

回答by tso

echo 'abc $def ghi' | sed 's/$//g'

In echo use single quote, if not it means that there is variable def and its substitution and if you don't have variable def it's empty. In sed, you need to escape the dollar sign, because otherwise it means "anchor to the end of the line."

在 echo 中使用单引号,如果没有,则表示存在变量 def 及其替换,如果没有变量 def 则为空。在 sed 中,您需要对美元符号进行转义,否则它意味着“锚定到行尾”。

回答by Siqueira

If you only want to remove the character '$' from the string, there is an alternative way using Shell Parameter Expansion. For example:

如果您只想从字符串中删除字符 '$',还有一种使用 Shell 参数扩展的替代方法。例如:

v1='abc $def ghi'
v2='abc 3def ghi'
echo ${v1/$/}
echo ${v2/$/}

The syntax is: ${parameter/pattern/string}

语法为:${parameter/pattern/string}

If you want to know more about Shell Parameters Expansion look at: https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html#Shell-Parameter-Expansion

如果您想了解有关 Shell 参数扩展的更多信息,查看:https: //www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html#Shell-Parameter-Expansion

回答by Andre Figueiredo

trshould be used for this task, not sed.

tr应该用于此任务,而不是sed.

Use it with single quotes in echoto prevent parameter expansion.

将它与单引号一起使用echo以防止参数扩展。

echo 'abc $123def ghi' | tr -d "$"

echo 'abc $123def ghi' | tr -d "$"