Mac OSX 与 grep (BSD grep) 2.5.1-FreeBSD
它看起来像 BSD grep 中的一个错误,这里还有一个相关主题:grep (BSD grep) 2.5.1-FreeBSD on mac os 10.8 line regexp mode not working with overlay patterns
我的 Mac OSX 10.9.1 上有相同版本的 grep (grep (BSD grep) 2.5.1-FreeBSD),它的行为完全相同。
带有 GNU grep 的 Ubuntu Precise
按预期工作。
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
带有 GNU grep 的 Mac OSX
按预期工作。
$ ggrep -V
ggrep (GNU grep) 2.14.56-1e3d
(...details removed...)
$ ggrep -x -f test1.txt test2.txt
foo
foo bar
解决方案#1:
如果你真的必须在 Mac OSX 上使用 BSD grep,这里有一些实际可行的方法:
$ grep -V
grep (BSD grep) 2.5.1-FreeBSD
$ grep -e "^foo$" -e "^foo bar$" test2.txt
foo
foo bar
解决方案#2:
通过自制软件安装 GNU grep:
$ 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
它将以ggrep
这种方式安装。还有一些方法可以安装grep
或替换系统 grep,不过我不会这样做(这是题外话)。无论如何安装后:
$ which ggrep
/usr/local/bin/ggrep