问题
It seems like the stock version of grep (version info: grep (BSD grep) 2.5.1-FreeBSD) under mac os 10.8 has an issue with patterns sharing a common prefix when being run in line regex mode (-x). In the following minimal example I would expect that grep reports "test" and "test2" but instead only "test" is reported. (Same also holds true for word regexp mode (-w)).
printf "test\ntest2\n" > f1.txt
printf "test\ntest2\n" > f2.txt
grep -x -F -f f1.txt f2.txt
Has anyone else made similar observations or even knows about a workaround?
回答1:
Verified; this does look like a bug in Apple and/or FreeBSD grep. (This is completely unsurprising to me; FreeBSD grep is a standards-hating pile of poo. My employer installs GNU grep on all our Mac systems rather than put up with FreeBSD's wacky behavior. And yes, GNU grep finds both lines in your example.)
If portability between Mac and Linux is an objective, I strongly recommend abandoning grep
altogether and just using perl
(or something like ack
, which depends on perl
).
@akostadinov's suggestion to put longer patterns before shorter ones in f2.txt does seem to work around the bug, but I would be leery of relying on something like that. It works on this toy example, but does it work in general, and how expensive will it be when you find out?
来源:https://stackoverflow.com/questions/12259484/grep-bsd-grep-2-5-1-freebsd-on-mac-os-10-8-line-regexp-mode-not-working-with-o