Why does this sed command for number matching not work?

My team is this:

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

(I use sed on a vanilla Mac)

I expect the result to be:

 Number cats 

However, the real result:

 12 cats 

Does anyone have any ideas about this? Thanks!

+6
source share
4 answers

Modifier + extension works for me:

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

In addition, the -E switch will make the + modifier work, see chorobas answer.

+9
source

+ must be inverse to get its special meaning.

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

Use perl, this will work on unix or linux.

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

In a very mystical sense, this is not explained (at least in the resources that I still have ..) You should check the following conditions:

globbing (in bash context), regular expression, extended regular expression

For your question, it seems that the expression you gave sed is a regular expression or an extended regular expression .... so in the tutorial that I read, you should also insert -r before your actual command in sed ...

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

Works for me on Ubuntu 16.04, bash.

0
source

Source: https://habr.com/ru/post/944633/


All Articles