Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this sed command to match number not work?

Tags:

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!

like image 263
Hanfei Sun Avatar asked May 09 '13 14:05

Hanfei Sun


People also ask

Why is sed not working?

Because you are using PCRE (Perl Compatible Regular Expressions) syntax and sed doesn't understand that, it uses Basic Regular Expressions (BRE) by default. It knows neither \s nor \d .

How do I change a number using sed?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.

How does the sed command work?

The sed command, short for stream editor, performs editing operations on text coming from standard input or a file. sed edits line-by-line and in a non-interactive way. This means that you make all of the editing decisions as you are calling the command, and sed executes the directions automatically.


2 Answers

+ must be backslashed to get its special meaning.

echo "12 cats" | sed 's/[0-9]\+/Number/g'
like image 91
choroba Avatar answered Oct 02 '22 00:10

choroba


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.

like image 37
zoul Avatar answered Oct 02 '22 00:10

zoul