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-ois used?Is there a portable way to express
^when-ois used that I can use with both Linux and MacOS?Is this a bug in BSD grep?
(echo ab; echo cd) | /usr/bin/egrep -o '^.'on OpenBSD 6.2 givesaand thencso it's probably at least a macOS bug – thrig Mar 05 '18 at 18:29a\nb\nc\nd\n. In that thegrepversion is2.5.1-FreeBSD. What version does OpenBSD have? – Digital Trauma Mar 05 '18 at 19:39a\nb\nc\nd\n(as another data point). – user4556274 Mar 05 '18 at 20:11