Linux 为什么这个匹配数字的 sed 命令不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16463938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:54:07  来源:igfitidea点击:

Why does this sed command to match number not work?

linuxbashshellsed

提问by Hanfei Sun

My command is like this:

我的命令是这样的:

echo "12 cats" | sed 's/[0-9]+/Number/g'

(I'm using the sedin vanilla Mac)

(我sed在香草 Mac 中使用)

I expect the result to be:

我希望结果是:

Number cats

However, the real result is:

然而,真正的结果是:

12 cats

Does anyone have ideas about this? Thanks!

有没有人对此有想法?谢谢!

采纳答案by zoul

Expanding the +modifier works for me:

扩展+修饰符对我有用:

echo "12 cats" | sed 's/[0-9][0-9]*/Number/g'

Also, the -Eswitch would make the +modifier work, see choroba's answer.

此外,-E开关将使+修改器工作,请参阅choroba 的回答。

回答by choroba

+must be backslashed to get its special meaning.

+必须反斜杠才能得到它的特殊含义。

echo "12 cats" | sed 's/[0-9]\+/Number/g'

回答by XY WANG

Use perl, this will work on unix or linux.

使用 perl,这将适用于 unix 或 linux。

echo "12 cats" | perl -pe 's/\d+/Number/g'

回答by YigalO

In a very mystic way that is not explained (at least in resources I have so far..), You should check up the next terms:

以一种没有解释的非常神秘的方式(至少在我目前拥有的资源中......),您应该检查下一个术语:

globbing (in the context of bash), regex, extended regex

通配(在 bash 的上下文中)、正则表达式、扩展正则表达式

For your question it seems that the expr' you gave to sed is a regex or extended regex....so by a tutorial I read you should insert also the -r before your actual command in sed...

对于您的问题,您提供给 sed 的 expr' 似乎是一个正则表达式或扩展正则表达式....所以通过我读过的教程,您还应该在 sed 中的实际命令之前插入 -r ...

echo "12 cats" | sed -r 's/[0-9]+/Number/g'

echo "12 只猫" | sed -r 's/[0-9]+/Number/g'

Works for me in an Ubuntu 16.04 , bash.

在 Ubuntu 16.04 bash 中对我有用。