我有一个文件,正在逐行阅读。有些行中有美元符号,我想使用sed删除它们。举个例子,
echo $line返回
{On the image of {$p$}-adic regulators},另一方面,
echo $line | sed 's/\$//g'正确返回
{On the image of {p}-adic regulators},但
title=`echo $line | sed 's/\$//g'`; echo $title返回
{On the image of {$p$}-adic regulators},发布于 2012-01-12 00:55:39
当在反号内使用sed命令时,需要转义该反斜杠:
title=`echo $line | sed 's/\\$//g'` # note two backslashes before $发布于 2012-01-12 00:51:38
使用variable substring replacement怎么样?这会产生相同的结果,而且效率会更高,因为它避免了仅仅为了运行sed而必须调用子外壳
[lsc@aphek]$ echo ${line//$/}
{On the image of {p}-adic regulators},如果你想继续使用sed ..。
您的问题是由于反引号语法(`...`)处理反斜杠的方式造成的。要避免此问题,请改用$()语法。
[me@home]$ title=$(echo $line | sed 's/\$//g'); echo $title
{On the image of {p}-adic regulators},请注意,不符合$()的旧版本bash可能不支持POSIX语法。如果您需要支持较旧的shell,则坚持使用反引号,但要转义反斜杠,如Simon's answer中所示。
有关详细信息,请参阅:BashFAQ: Why is $(...) preferred over `...` (backticks)。
发布于 2012-01-12 00:56:24
由于已经发布了sed解决方案,因此这里有一个awk变体。
[jaypal:~/Temp] awk '{gsub(/\$/,"",$0);print}' <<< $line
{On the image of {p}-adic regulators},所以你可以这样做-
[jaypal:~/Temp] title=$(awk '{gsub(/\$/,"",$0);print}' <<< $line); echo $title
{On the image of {p}-adic regulators},https://stackoverflow.com/questions/8823113
复制相似问题