sed 行为与 &(与号) [英] sed behavior with & (ampersand)

查看:46
本文介绍了sed 行为与 &(与号)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图清理一些看起来像

Trying to clean up some xml text that looks like

Forest & Paper Products Manufacturing

使用像 sed 命令

 sed "s/ \& / & /"

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

but once sed gets done with the file, my output looks like

Forest & amp; Paper Products Manufacturing

无法弄清楚为什么 sed 在 &

Can't figure out why sed is putting a space after the &

我可以解决这个问题:

sed "s/ \& / \& /"

但是为什么我需要引用 &带有 \ 前缀

But why do I need to quote the & with a \ prefix

推荐答案

在替换部分,&表示匹配的字符串\0.因此,如果您想在替换部分中使用文字 &,则必须对其进行转义.

in the replacement part, & indicates the matched string \0. So if you want to have literal & in replacement part, you have to escape it.

例如

kent$ (master|✔) echo "foo"|sed 's/.*/&_bar/'   
foo_bar

kent$ (master|✔) echo "foo"|sed 's/.*/\&_bar/' 
&_bar

从 sed 的 INFO 页面获取的相关信息:

related info taken from sed's INFO page:

   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

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

这篇关于sed 行为与 &(与号)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆