$ awk 'NR==FNR { a[$1]++ ; next}; $1 in a' file2 file1
c cat
e eagle
f fire
This reads in file2
(the first filename argument) and stores it in array a
. It detects whether it is reading the first file by checking whether NR
(the total number of input records seen so far) is equal to FNR
(the input record number of the current input file)
Then it reads file1
(the second filename argument) and if the first field is in array a
, it prints the matching input line (in awk
, the default action on any successful test result, such as $1 in a
, is to print the input line - so $1 in a
by itself is equivalent to $1 in a {print}
).
BTW, in many cases, tasks like this can be done with grep -f file2 file1
but that will match the contents of file2 anywhere in file1 - e.g. c
from file2 would match not only cat
but also jack
in file1.