Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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)

share|improve this question
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
show 1 more comment

1 Answer

up vote 4 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
add comment

Your Answer

 
discard

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.