Macos 使用';从文件中读取grep模式-x';(精确的线匹配)。。。模式顺序重要吗?

Macos 使用';从文件中读取grep模式-x';(精确的线匹配)。。。模式顺序重要吗?,macos,grep,Macos,Grep,刚开始使用grep,有一个奇怪的问题让我很困惑。我创建了两个相同的文件: test1.txt foo foo bar foo bar foo test2.txt foo foo bar 当我运行grep-x-f test1.txt test2.txt时,我希望得到foo和foo-bar,但我得到的只是foo。但是,如果我在test1.txt中切换模式的顺序,如下所示: test1.txt foo foo bar foo bar foo 现在,当我运行grep-x-f test1.txt

刚开始使用grep,有一个奇怪的问题让我很困惑。我创建了两个相同的文件:

test1.txt

foo
foo bar
foo bar
foo
test2.txt

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

test1.txt

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

Mac OSX with grep(BSD grep)2.5.1-FreeBSD 这看起来像是BSD grep中的一个bug,下面是一个相关主题:

我在Mac OSX 10.9.1上有相同版本的grep(grep(BSD grep)2.5.1-FreeBSD),其行为完全相同

UbuntuPrecision与GNUgrep 一切正常

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
$ ggrep -V
ggrep (GNU grep) 2.14.56-1e3d
(...details removed...)
$ ggrep -x -f test1.txt test2.txt
foo
foo bar
带有GNU grep的Mac OSX 一切正常

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
$ 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

它是什么操作系统?我假设它是Linux?我尝试了同样的方法,但得到了预期的答案…你能尝试grep-x-f text1.txt text1.txt1.txt1
grep-x-f test1.txt test1.txt
但仍然只得到了
foo
。然而,在切换模式顺序后,运行
grep-x-f test1.txt test1.txt
给出了我想要的:e> foo bar和
foo
@andros Do
cat-vet
在这两个文件上查找尾随空格。感谢您的提示。尽管已检查,但没有尾随空格。