Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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)

share|improve this question
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
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
up vote 6 down vote accepted

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
share|improve this answer
The mystery is solved, thanks! – Acorn Mar 9 '11 at 10:50
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

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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