BSD grep returning incorrect results

When executing grep on OSX my results are incorrect. I’m looking for the offset of a substring with several matches, using -aob. ‘a’ indicating that i’m using strings, ‘o’ only showing the result, and ‘b’ for the byte offset.

echo "ABDABCABC" | grep -aob "ABC"

With the output:

0:ABC
ABC

When in fact the output should be:

3:ABC
6:ABC

By default OSX uses BSD grep, which seems to have this problem. I’m using El Capitan, but other Mac users with earlier versions experience the same. I’ve tried installing GNU grep through homebrew. I can’t seem to use it for grep though, grep -V return that it’s using the BSD. MacPorts is having some issues right now, so I can’t use that for installing.

I’ve also updated bash to the latest version, so I’m fairly certain that this isn’t the source of my troubles.

On another note using Perl alternatives for grep isn’t an option, this is for a homework assignment and one of the conditions is to not use Perl.

Does anyone have a solution for this? Either to fix the issue with BSD or a way to use an installed homebrew GNU grep.
Cheers.


Source: bash

Leave a Reply