我有这个命令字符串,它在 OS X 10.6.8 (Snow Leopard) 中运行良好(它告诉我它的 grep 是 grep (GNU grep) 2.5.1)...
$ grep -hi 'TERM' file1.txt | cut -d '|' -f 3 | grep -f - file2.txt
(在文件 1 中查找所有包含 TERM 的行,将每一行缩减为字段 3 中的唯一 ID 号,然后在文件 2 中查找这些 ID)
然而这在 OS X 10.11.5 (El Capitan) 中失败了(它告诉我它的 grep 是 grep (BSD grep) 2.5.1-FreeBSD)...
grep: -: No such file or directory
我真的不想在这台机器上安装 GNU grep。有没有办法修复第二个 grep 命令,以便 BSD grep 可以工作?或者更好的方法来解决这个问题?
一些示例代码:
file1.txt 看起来像:
Jones Inc||000123||foo||bar
TerminatorLLC||000124||foo||bar
Conan LP||000125||foo||bar
Termites-R-Us||000126||foo||bar
file2.txt 类似:
000123||210 Main Street||moo||car
000124||Los Angeles||moo||car
000125||Mythical Kingdom||moo||car
000126||Your Woodwork||moo||car
最佳答案
-
通常指标准输入或标准输出,-f
将在 B 中搜索来自 A 的行:
grep -f A B
<(...)
(称为 process substitution )将生成一个输出为 ...
的"file" :
% echo <(ls)
/dev/fd/63
有了这些知识,您可以将命令更改为:
grep -f <(grep -hi 'TERM' file1.txt | cut -d '|' -f 3) file2.txt
在 AWK 中:
awk -F'|' 'NR == FNR { if ( /[tT][eE][rR][mM]/ ) a[$3] = 1; next }a[$1]' file1.txt file2.txt
以及 @fedorqui 建议的替代方案, 但修改为不使用 gawk's IGNORECASE
.请注意,文件被读取 file2.txt
file1.txt
awk -F'|' 'NR == FNR { a[$1] = $0; next } /[tT][eE][rR][mM]/ { print a[$3] }' file2.txt file1.txt
关于bash - 管道搜索模式到 BSD grep,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37609129/