就地 sed 命令不起作用 [英] In-place sed command not working

查看:62
本文介绍了就地 sed 命令不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 GNU Sed,我总是在就地替换方面遇到一些麻烦.在这种情况下,我试图从如下所示的 xml 条目中删除一些逗号:

Using GNU Sed, I always have some sort of trouble with the in-place substitution. In this case, I'm trying to remove some commas from xml entries that look like this:

<address>T/A Business Name, 74, Address Line 1, Some Town, Some City</address>

...特别是地址号后面的逗号(例如 74)需要删除.所以我正在使用这样的东西:

...in particular the comma after the address number (e.g. 74) needs to be removed. So I'm using something like this:

sed -nr 's!(<address>T/A\s+.*?,\s*[0-9]+\s*),(.*</address>)!\1\2! p'

这会打印出将完全按照我的预期更改的行,即删除地址号后的逗号.但是当我更改命令以实际对文件进行就地更改时,如下所示:

And that prints out the lines that will be changed exactly as I would expect them i.e. the commas after the address numbers are removed. But when I change the command to actually make the changes to the files in-place, like this:

sed -ir 's!\(<address>T/A\s+.*?,\s*[0-9]+\s*\),\(.*</address>\)!\1\2!'

但是该命令什么也不做.没有进行任何更改,但它是完全相同的命令,除了这次我必须转义捕获括号,否则每个匹配行都会出现错误,例如:

But the command does nothing. No changes are made but it's the exact same command, except that I had to escape the capture parentheses this time or else I got errors for every matching line like:

sed: -e expression #1, char 62: invalid reference \2 on `s' command's RHS

推荐答案

你也可以试试这个,

sed -ri 's~^(.*Name, [0-9]+),(.*)$~\1\2~g' file

不要在 sed 中的 -r 之前使用 -i.如果这样做,它会显示如上所示的错误消息.

Don't use -i before -r in sed. If you do so, it displays an error message like above.

示例:

$ cat aa
<address>T/A Business Name, 74, Address Line 1, Some Town, Some City</address>

$ sed -r 's~^(.*Name, [0-9]+),(.*)$~\1\2~g' aa
<address>T/A Business Name, 74 Address Line 1, Some Town, Some City</address>

这篇关于就地 sed 命令不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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