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:


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)

  • 3
    This gives just 1/2/ for me on Debian Squeeze with GNU grep 2.6.3. Maybe you should add some more specific details about your distro and grep version. – Arrowmaster Mar 9 '11 at 4:05
  • as @Arrowmaster, tested on Ubuntu 10.10, with grep 2.6.3-3 – simon Mar 9 '11 at 4:45
  • 1
    Tested on GNU/Linux with GNU grep 2.5.1 and showing result as @Acorn . – chanchal1987 Mar 9 '11 at 6:14
  • Works for me with GNU grep 2.5.4 – zarkdav Mar 9 '11 at 7:07
  • @ Zarkdav,its not working for me on GNU grep 2.5.4 echo "1/2/3/4/5" | grep -oE "^([^/]+/){0,2}" 1/2/ – sush Mar 9 '11 at 7:11

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
| improve this answer | |
  • 3
    This bug, where grep -o/grep --only-matching allows a caret to match after the end of a previous match instead of only at beginning of line, is still present in Mac OS X 10.9.4. – Robert Tupelo-Schneck Aug 22 '14 at 13:22
  • This bug is still present today at the end of 2020, in Mac OS X Catalina 10.15.7. That's 9 years, 8 months after this question was posted. This was driving me crazy: surely there can't be a BUG IN GREP??? But alas, there is. – David M. Perlman Nov 26 at 6:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.