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?

Digital Trauma
  • 8,404
  • 2
  • 23
  • 39
  • 2
    `(echo ab; echo cd) | /usr/bin/egrep -o '^.'` on OpenBSD 6.2 gives `a` and then `c` so it's probably at least a macOS bug – thrig Mar 05 '18 at 18:29
  • @thrig interesting. I just tried FreeBSD 11 and your test yields `a\nb\nc\nd\n`. In that the `grep` version is `2.5.1-FreeBSD`. What version does OpenBSD have? – Digital Trauma Mar 05 '18 at 19:39
  • 1
    On OpenBSD 5.8, I get `a\nb\nc\nd\n` (as another data point). – user4556274 Mar 05 '18 at 20:11
  • A related question is https://unix.stackexchange.com/questions/398223/ . – JdeBP Mar 06 '18 at 08:31

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.

Digital Trauma
  • 8,404
  • 2
  • 23
  • 39
  • 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