问题描述:

I have this command string which worked perfectly well in OS X 10.6.8 (Snow Leopard) (which tells me its grep is grep (GNU grep) 2.5.1)...

$ grep -hi 'TERM' file1.txt | cut -d '|' -f 3 | grep -f - file2.txt

(Finding all lines with TERM in them in file1, cutting each down to the unique ID number in field 3, then looking up those IDs in file2)

And yet this fails in OS X 10.11.5 (El Capitan) (which tells me its grep is grep (BSD grep) 2.5.1-FreeBSD)...

grep: -: No such file or directory

I really don't want to install GNU grep on this machine. Is there a way to fix the second grep command so BSD grep will work? Or a better way to go about it generally?

Some sample code:

file1.txt would look like:

Jones Inc||000123||foo||bar

TerminatorLLC||000124||foo||bar

Conan LP||000125||foo||bar

Termites-R-Us||000126||foo||bar

file2.txt like:

000123||210 Main Street||moo||car

000124||Los Angeles||moo||car

000125||Mythical Kingdom||moo||car

000126||Your Woodwork||moo||car

网友答案:

- usually refers to stdin or stdout, -f will search B for lines from A:

grep -f A B

<(...) (called process substitution) will make a "file" with the output of ...:

% echo <(ls)
/dev/fd/63    

You can with this knowledge change the commands to:

grep -f <(grep -hi 'TERM' file1.txt | cut -d '|' -f 3) file2.txt

And in AWK:

awk -F'|' 'NR == FNR { if ( /[tT][eE][rR][mM]/ ) a[$3] = 1; next }a[$1]' file1.txt file2.txt

And alternative as suggested by @fedorqui, but modified to not use gawk's IGNORECASE. Note that the files are read file2.txt file1.txt

awk -F'|' 'NR == FNR { a[$1] = $0; next } /[tT][eE][rR][mM]/ { print a[$3] }' file2.txt file1.txt
相关阅读:
Top