Reputation: 153
New to using grep, and having a weird issue that's got me stumped. I created two identical files:
test1.txt
foo
foo bar
test2.txt
foo
foo bar
When I run grep -x -f test1.txt test2.txt
, I expect to get foo
and foo bar
, but all I get is foo
. But then, if I switch the order of the patterns in test1.txt as follows:
test1.txt
foo bar
foo
Now, when I run grep -x -f test1.txt test2.txt
, I get what I want: foo
and foo bar
. Why? :( Also, is there a way to make this work without re-arranging the order of the patterns? (This is part of a larger project, and there are many examples of this.) Thank you!
Upvotes: 3
Views: 1118
Reputation: 6413
It looks like a bug in BSD grep, here is a related topic also: grep (BSD grep) 2.5.1-FreeBSD on mac os 10.8 line regexp mode not working with overlapping patterns
I have the same version of grep (grep (BSD grep) 2.5.1-FreeBSD) on my Mac OSX 10.9.1 and it behaves exactly the same.
Works as expected.
vagrant@precise64:~$ grep -V
grep (GNU grep) 2.10
(...details removed...)
vagrant@precise64:~$ echo -e 'foo\nfoo bar' > test1.txt && cp test1.txt test2.txt
vagrant@precise64:~$ grep -x -f test1.txt test2.txt
foo
foo bar
Works as expected.
$ ggrep -V
ggrep (GNU grep) 2.14.56-1e3d
(...details removed...)
$ ggrep -x -f test1.txt test2.txt
foo
foo bar
Sulution #1:
If you really have to use BSD grep on Mac OSX, here is something that actually works:
$ grep -V
grep (BSD grep) 2.5.1-FreeBSD
$ grep -e "^foo$" -e "^foo bar$" test2.txt
foo
foo bar
Sulution #2:
Install GNU grep via homebrew:
$ brew tap homebrew/dupes
Cloning into '/usr/local/Library/Taps/homebrew-dupes'...
remote: Reusing existing pack: 1083, done.
remote: Counting objects: 9, done.
remote: Compressing objects: 100% (7/7), done.
remote: Total 1092 (delta 3), reused 8 (delta 2)
Receiving objects: 100% (1092/1092), 216.09 KiB | 278.00 KiB/s, done.
Resolving deltas: 100% (559/559), done.
Checking connectivity... done
Tapped 39 formula
$ brew install grep
(...installing...)
usr/local/Cellar/grep/2.15: 13 files, 872K, built in 40 seconds
It will be installed as ggrep
this way. There are ways to install as grep
also, or replace system grep, I wouldn't do that though (this is offtopic).
Anyway after installing:
$ which ggrep
/usr/local/bin/ggrep
Upvotes: 3