bash 有没有一种方法可以通过 sed 从字符串中删除美元符号?

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

Is there a one line way to remove dollar signs from a string via sed?

bashsed

提问by David Zureick-Brown

I have a file and am reading it line by line. Some lines have dollar signs in them, and I would like to remove them using sed. So for instance,

我有一个文件,正在逐行阅读。有些行中有美元符号,我想使用 sed 删除它们。所以例如,

echo $line

returns

回报

{On the image of {$p$}-adic regulators},

On the other hand,

另一方面,

          echo $line | sed 's/$//g'

correctly returns

正确返回

 {On the image of {p}-adic regulators},

but

 title=`echo $line | sed 's/$//g'`; echo $title

returns

回报

 {On the image of {$p$}-adic regulators},

回答by Simon Whitaker

You need to escape the backslash in your sed command when using it within backticks:

在反引号中使用时,您需要转义 sed 命令中的反斜杠:

title=`echo $line | sed 's/\$//g'` #?note two backslashes before $

回答by Shawn Chin

How about using variable substring replacement. This gives the same results and should be more efficient as it avoids having to invoke a subshell just to run sed:

如何使用可变子字符串替换。这给出了相同的结果并且应该更有效,因为它避免了为了运行而调用子shell sed

[lsc@aphek]$ echo ${line//$/}
{On the image of {p}-adic regulators},


If you wish to stick with sed...

如果你想坚持sed...

You problem is due to the way the backtick syntax (`...`) handles backslashes. To avoid the problem, use the $()syntax instead.

您的问题是由于反引号语法 ( `...`) 处理反斜杠的方式造成的。为避免此问题,请改用$()语法。

[me@home]$ title=$(echo $line | sed 's/$//g'); echo $title
{On the image of {p}-adic regulators},

Note that the $()syntax may not be supported by older versions of bash that are not POSIX compliant. If you need to support older shells, then stick to the backticks but escape the backslashes as shown in Simon's answer.

请注意,$()不符合 POSIX 的较旧版本的 bash 可能不支持该语法。如果您需要支持较旧的 shell,请坚持使用反引号,但要避开反斜杠,如Simon 的回答所示。

For more details, see: BashFAQ: Why is $(...) preferred over `...`(backticks).

有关更多详细信息,请参阅:BashFAQ:为什么 $(...) 优先于`...`(backticks)

回答by jaypal singh

Since sedsolution has already been posted, here is an awkvariant.

由于sed解决方案已经发布,这里是一个awk变体。

[jaypal:~/Temp] awk '{gsub(/$/,"",
[jaypal:~/Temp] title=$(awk '{gsub(/$/,"",##代码##);print}' <<< $line); echo $title
{On the image of {p}-adic regulators},
);print}' <<< $line {On the image of {p}-adic regulators},

So you can do something like this -

所以你可以做这样的事情 -

##代码##