3

刚开始使用 grep,遇到了一个让我难过的奇怪问题。我创建了两个相同的文件:

test1.txt

foo
foo bar

test2.txt

foo
foo bar

当我跑步时grep -x -f test1.txt test2.txt,我希望得到fooand foo bar,但我得到的只是foo. 但是,如果我在 test1.txt 中切换模式的顺序如下:

test1.txt

foo bar
foo

现在,当我运行时grep -x -f test1.txt test2.txt,我得到了我想要的:foofoo bar. 为什么?:(另外,有没有办法在不重新安排模式顺序的情况下完成这项工作?(这是一个更大项目的一部分,有很多这样的例子。)谢谢!

4

1 回答 1

3

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
于 2014-01-22T00:22:48.043 回答