Grep Regex – Troubleshooting Grep -o Regex Issues

grepregular expression

I'm trying to use a grep command with the –only-matching flag, but it's not behaving as I would expect it to.

This command:

echo "1/2/3/4/5" | grep -oE "^([^/]+/){0,2}"

Gives this output:

1/2/
3/4/

I was expecting just 1/2/

What's going on..? 3/4/ shouldn't match "^([^/]+/){0,2}" because it's not at the beginning of the line..

(running GNU grep 2.5.1)

Best Answer

It was a bug in versions of GNU Grep earlier than this commit (i.e. earlier than GNU version 2.5.3).

Quoting the relevant part of the changelog:

Previously failing tests relative to left anchors (^ and \<) and -w should now pass.

The initial commit that described the bug also added a test for it:

# End of a previous match should not match a "start of ..." expression.
grep_test "word_word/" "word_/" "^word_*" -o
Related Question