Ankur Agarwal
Ankur Agarwal

Reputation: 24768

Interesting grep match in bash

Can you explain why

This one gives $? = 1

echo "uus" | grep -w -o [0123456789]\*

and this one give $? = 0

echo "-uus" | grep -w -o [0123456789]\*

Upvotes: 1

Views: 314

Answers (2)

William Pursell
William Pursell

Reputation: 212298

grep is matching the zero length word between '-' and 'u'.

Upvotes: 0

rob mayoff
rob mayoff

Reputation: 385710

Your regular expression can match an empty string. The -w flag means that any match must be preceded by beginning-of-line or a non-word character, and followed by end-of-line or a non-word character.

In the case of uus, the beginning of line is followed be a word character, so grep can't match an empty string as a word there. The end of line is preceded by a word character, so grep can't match an empty string as a word there.

In the case of -uus, the beginning of line is followed by -, which is a non-word character, so grep can match the empty string as a word between the beginning of the line and the - character.

Upvotes: 5

Related Questions