使用 sed 正则表达式分组替换字符
我有一个像这样的文本文件:
FOO BAR PIPPO PLUTO 31337 1010
FOOZ BAZ 130
VERY LONG LINE LIKE THIS THEN A NUMBER LIKE 42
我需要将其转换为:
FOO-BAR-PIPPO-PLUTO 31337 1010
FOOZ-BAZ 130
VERY-LONG-LINE-LIKE-THIS-THEN-A-NUMBER-LIKE 42
我能做的最好的事情是:
sed -re 's/([A-Z]+)( )([A-Z]+)/\1-\3/g'
但输出是
FOO-BAR PIPPO-PLUTO 31337 1010
FOOZ-BAZ 130
VERY-LONG LINE-LIKE THIS-THEN A-NUMBER LIKE 42
关闭,但没有雪茄。知道为什么我的正则表达式不起作用吗?
I have a text file that is like this:
FOO BAR PIPPO PLUTO 31337 1010
FOOZ BAZ 130
VERY LONG LINE LIKE THIS THEN A NUMBER LIKE 42
I need to turn it into:
FOO-BAR-PIPPO-PLUTO 31337 1010
FOOZ-BAZ 130
VERY-LONG-LINE-LIKE-THIS-THEN-A-NUMBER-LIKE 42
The best I could do is:
sed -re 's/([A-Z]+)( )([A-Z]+)/\1-\3/g'
but the output is
FOO-BAR PIPPO-PLUTO 31337 1010
FOOZ-BAZ 130
VERY-LONG LINE-LIKE THIS-THEN A-NUMBER LIKE 42
Close, but no cigar. Any idea on why my regex doesn't work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不能有重叠的匹配。未检测到“BAR PIPPO”,因为在匹配“FOO BAR”时“BAR”已被消耗。
请尝试以下操作:
请注意,这没有重叠的匹配项:
You can't have overlapping matches. "BAR PIPPO" isn't detected because "BAR" was already consumed when matching "FOO BAR".
Try this instead:
Note that this doesn't have overlapping matches:
只需查找后跟非数字的空格并将该空格替换为
-
。这样做的优点是它适用于包含非字母数字字符的行。概念验证
Just look for space followed by not a number and replace that space with a
-
. The advantage of this is that it will work for lines that have non-alphanumeric characters.Proof of Concept
非常接近。不过,您不需要匹配多个字母 - 您只需要字母空格字母:(
针对 BSD sed 调整 sed 参数)
Very close. You don't need to match more than one letter though - you just want letter space letter:
(sed params adjusted for BSD sed)