views:

65

answers:

3

Can someone explain why this code doesn't work as expected? I would expect it only to match the first character, and it does with literal characters, but the wildcard (.) and characters classes behave strangely:

I use -o just to demonstrate exactly how things are matching, it doesn't change what matches at all.

$ echo foo | grep -o '^.'
f
o
o

Some more unexpected behavior:

$ echo foobarbazquux | grep -o '^[foarqux]'
f
o
o

$ echo foobarbazquux | grep -o '^.[^u]'
fo
ob
ar
ba
zq

Esentially the beginning-of-line matcher (^) is not behaving as expected in these cases. Is there any way to make it behave more normally?

A: 

Your results can't be correct:

sirrus@it:~$ echo foobarbazquux | grep -o '^[foarqux]'
f

Is correct - grep got olny one line!

I do not know what you did - but your input can't match the output you provide.

Sorry - this should be a comment - but it was not readable.

Andreas Rehm
Works like the OP on my Mac
Colin Hebert
it's a bug - it should not work. ^ matches the beginning of one line! If you provide one line it can match only one line - otherwise it's a bug. And it's a really old one!
Andreas Rehm
A: 

From my Ubuntu 10.04 box:

marc@panic:~$ echo foo | grep -o '^.'
f
marc@panic:~$ echo foobarbazquux | grep -o '^[foarqux]'
f
marc@panic:~$ echo foobarbazquux | grep -o '^.[^u]'
fo
marc@panic:~$ grep --version
GNU grep 2.5.4

There are a series of environment variables grep will look for to control its behavior/output, so check if any of those are set. Most likely you've got 'GREP_OPTIONS' set.

Marc B
2.5.1 here, behaves like bukzor's, see my comment to the question.
ninjalj
I get the same behavior as OP even if I use `env -i` to clear out the environment.
John Kugelman
+5  A: 

Found it:

Bug

Changelog of fix

Apparently fixed in 2.5.2. Found it via launchpad.

ninjalj