Use grep
:
grep -Fwf file1 file2
from man grep
:
-F, --fixed-strings
Interpret PATTERN as a list of fixed strings (instead of regular expressions), separated by
newlines, any of which is to be matched.
-f FILE, --file=FILE
Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with
the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and
therefore matches nothing.
-w, --word-regexp
Select only those lines containing matches that form whole words. The test is that the matching
substring must either be at the beginning of the line, or preceded by a non-word constituent
character. Similarly, it must be either at the end of the line or followed by a non-word
constituent character. Word-constituent characters are letters, digits, and the underscore.
Or awk
:
awk 'NR==FNR{seen[$0]++} ($2 in seen)' file1 file2
At above, first we are reading the file1 and holds the entire column1 from into an array named seen, then look in file2 on its second column and if it's matched with the saved column1 from file1 then goes to print entire row of file2.
You also have join
command if both files are sorted (if not, you can pass sorted output by sort
ing):
join -1 1 -2 2 file1 file2
from man join
-1 FIELD
join on this FIELD of file 1
-2 FIELD
join on this FIELD of file 2
if files are not sorted:
join -1 1 -2 2 <(sort file1) <(sort file2)