Why does this sed command to match number not work?

匿名 (未验证) 提交于 2019-12-03 01:33:01

问题:

My command is like this:

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

(I'm using the sed in vanilla Mac)

I expect the result to be:

Number cats 

However, the real result is:

12 cats 

Does anyone have ideas about this? Thanks!

回答1:

Expanding the + modifier works for me:

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

Also, the -E switch would make the + modifier work, see choroba’s answer.



回答2:

+ must be backslashed to get its special meaning.

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


回答3:

Use perl, this will work on unix or linux.

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


回答4:

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

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...

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

Works for me in an Ubuntu 16.04 , bash.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!