File Comparison – Comparing First Column of Two Files and Printing Matching Rows

awkgrepjoin;

I have two files in these formats:

file1 :

air
smell
hand
dude
road
cat

file 2:

air,4,21,01,13,3,2
smell,21,4,2,5,6
dude,1,31,42,1
road,1,4,2,1,4
cat,1,5,6,3,1
hand,1,4,2,1,6
mouse,1,3,5,6,2

what I want to do is print the entire row of file 2, if the first string in column 1 of file 2 is found in file 1, and I want to keep the order of file 1.

expected output:

air,4,21,01,13,3,2
smell,21,4,2,5,6
hand,1,4,2,1,6
dude,1,31,42,1
road,1,4,2,1,4
cat,1,5,6,3,1

Best Answer

This should do it:

awk -F, 'FNR==NR {a[$1]; next}; $1 in a' file1 file2

edit:

Interpreted the wrong file for the ordering. A new attempt (requires gawk if that is acceptable)

gawk -F, '
    FNR==NR {a[NR]=$1; next}; 
    {b[$1]=$0}
    END{for (i in a) if (a[i] in b) print b[a[i]]}
' file1 file2

edit 2:

With nowmal awk, and swapping the files around:

awk -F, 'FNR==NR {a[$1]=$0; next}; $1 in a {print a[$1]}' file2 file1
Related Question