与&的sed行为(符号)

时间:2015-09-23 22:33:46

标签: sed

尝试清理一些看起来像

的xml文本
Forest & Paper Products Manufacturing

使用像

这样的sed命令
 sed "s/ \& / & /"

但是一旦sed完成了文件,我的输出看起来像

Forest & amp; Paper Products Manufacturing

无法弄清楚为什么sed会在&

之后放置一个空格

我可以用以下方法解决这个问题:

sed "s/ \& / \& /"

但为什么我需要引用&使用\前缀

1 个答案:

答案 0 :(得分:9)

在替换部分中,\0表示匹配的字符串&。因此,如果您想在替换部分中使用文字kent$ (master|✔) echo "foo"|sed 's/.*/&_bar/' foo_bar kent$ (master|✔) echo "foo"|sed 's/.*/\&_bar/' &_bar ,则必须将其转义。

E.g

   The REPLACEMENT can contain `\N' (N being a number from 1 to 9,
 inclusive) references, which refer to the portion of the match which
 is contained between the Nth `\(' and its matching `\)'.  Also, the
 REPLACEMENT can contain unescaped `&' characters which reference the
 whole matched portion of the pattern space

相关信息来自sed的INFO页面:

To include a literal `\', `&', or newline in the final replacement, be   
 sure to precede the desired `\', `&', or newline in the REPLACEMENT with 
 a `\'.

getContentPane()