2

I'm trying to match the first character on a line with grep, and print only that character. With GNU grep 2.20 in Linux I do something like this:

$ echo ab | grep -o '^.'
a
$ 

This is works as I expect it - the ^ anchors the regexp to the start of the line and only the a character is printed.

However with BSD grep 2.5.1 on MacOS I get a different result:

$ echo ab | egrep -o '^.'
a
b
$

It is as if the ^ start-of-line anchor is being ignored. Interestingly the $ end-of-line anchor works as expected on both grep flavours:

$ echo ab | grep -o '.$'
b
$ 

Interestingly, BSD grep does respect the ^ start-of-line anchor if the -o option is not used:

$ { echo a ; echo b; } | grep '^a'
a
$  
  • Does BSD grep have some other way to express ^ when -o is used?

  • Is there a portable way to express ^ when -o is used that I can use with both Linux and MacOS?

  • Is this a bug in BSD grep?

1 Answers1

2

Digging a bit deeper, I found this behavior reported in a FreeBSD bug:

I've noticed some more issues with the same version of grep. I don't know whether they're related, but I'll append them here for now.

$ printf abc | grep -o '^[a-c]'

should just print 'a', but instead gives three hits, against each letter of the incoming text.

But it's not clear to me if or when this will be fixed.

  • It seems clear to me that the base system grep on FreeBSD is GNU grep and that there are plans to replace it within a short enough time (a couple of years or so) for them not to bother fixing the bug right now at least. – Kusalananda Mar 05 '18 at 21:07
  • The questioner is using MacOS, not FreeBSD, Kusalananda. – JdeBP Mar 06 '18 at 08:34