Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd grep behavior

Tags:

grep

bash

Motivated by this question, can anyone explain the following behavior?

$ echo "-uus" | grep -wo '[0]*' && echo matched
-uus

matched
$ echo "-uus" | grep -o '[0]*' && echo matched
matched
$ grep --version | sed 1q
grep (GNU grep) 2.5.1

In particular, why does the second grep succeed, but generate no output? And why does the first command have two lines of output? I can understand the second line of output, but I do not understand the first.

like image 396
William Pursell Avatar asked Oct 09 '22 19:10

William Pursell


2 Answers

There were bugs in the older versions of grep. I reported one here:

https://bugzilla.redhat.com/show_bug.cgi?id=144980

Newer versions of grep do not exhibit the problem anymore.

like image 184
choroba Avatar answered Oct 13 '22 09:10

choroba


Question: Why does the grep succeed, but generate no output?

$ echo "-uus" | grep -o '[0]*' && echo matched
matched

Answer:

The pattern [0]* means at least zero character. So grep says it finds it, even if the matched text is empty. grep used with option -o does not print empty matched string. The man page says:

-o, --only-matching
Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.

You can even use an empty pattern, it outputs the same:

$ echo "-uus" | grep -o '' && echo matched 
matched

You can also test:

$ echo    | grep -o '' && echo matched || echo unmatched
matched
$ echo -n | grep -o '' && echo matched || echo unmatched
unmatched

However grep prints even the empty lines when the option -o is not used:

$ echo    | grep '' && echo matched || echo unmatched

matched


Question: Why does the first command have two lines of output?

$ echo "-uus" | grep -wo '[0]*' && echo matched
-uus

matched
$ grep --version | sed 1q
grep (GNU grep) 2.5.1

Answer:

Looks like a bug in GNU grep 2.5.1

like image 22
oHo Avatar answered Oct 13 '22 09:10

oHo