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.
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.
grep
succeed, but generate no output?$ echo "-uus" | grep -o '[0]*' && echo matched
matched
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
$ echo "-uus" | grep -wo '[0]*' && echo matched
-uus
matched
$ grep --version | sed 1q
grep (GNU grep) 2.5.1
Looks like a bug in GNU grep 2.5.1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With