是否有单行方式通过sed从字符串中删除美元符号?

Dav*_*own 3 bash sed

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

echo $line
Run Code Online (Sandbox Code Playgroud)

回报

{On the image of {$p$}-adic regulators},
Run Code Online (Sandbox Code Playgroud)

另一方面,

          echo $line | sed 's/\$//g'
Run Code Online (Sandbox Code Playgroud)

正确回归

 {On the image of {p}-adic regulators},
Run Code Online (Sandbox Code Playgroud)

 title=`echo $line | sed 's/\$//g'`; echo $title
Run Code Online (Sandbox Code Playgroud)

回报

 {On the image of {$p$}-adic regulators},
Run Code Online (Sandbox Code Playgroud)

Sim*_*ker 9

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

title=`echo $line | sed 's/\\$//g'` # note two backslashes before $
Run Code Online (Sandbox Code Playgroud)


Sha*_*hin 6

如何使用变量子串替换.这给出了相同的结果,并且应该更有效,因为它避免了只需要运行子shell来运行sed:

[lsc@aphek]$ echo ${line//$/}
{On the image of {p}-adic regulators},
Run Code Online (Sandbox Code Playgroud)

如果你想坚持sed......

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

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

请注意,$()不符合POSIX标准的旧版本bash可能不支持该语法.如果你需要支持较旧的炮弹,那么坚持反击,但是如Simon的回答所示,逃避反斜杠.

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