使用' -x'从文件中读取grep模式(确切的行匹配)...模式顺序是否重要?

时间:2013-05-29 16:35:05

标签: macos grep

使用grep的新手,并且有一个令我难过的奇怪问题。我创建了两个相同的文件:

test1.txt的

foo
foo bar

的test2.txt

foo
foo bar

当我运行grep -x -f test1.txt test2.txt时,我希望获得foofoo bar,但我得到的只是foo。但是,如果我按照以下方式切换test1.txt中模式的顺序:

test1.txt的

foo bar
foo

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

1 个答案:

答案 0 :(得分:2)

Mac OSX with 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 overlapping 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


Sulution#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

Sulution#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,我不会这样做(这是offtopic)。 无论如何安装后:

$ which ggrep
/usr/local/bin/ggrep