This question already has an answer here:

I have file1 and file2 as following. I would like to first find matches between two files based on first column and then print the matching lines from file1 and file2. I have written the desired output below

$ cat file1
1,      456,    abcd,  ...
23,     567,    rstc,  ...
45,     678,    rsto,  ...
$ cat file2
23,     5607,   abcstc, ...
45,     28,     zfgsto, ...

Desired output:

23,     567,    rstc,    ...
23,     5607,   abcstc,  ...
45,     678,    rsto,    ...
45,     28,     zfgsto,  ...

marked as duplicate by muru, Eric Carvalho, Fabby, mikewhatever, g_p Jan 31 '15 at 14:51

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • The answers available are only for one file and not for comparing two different files – Trupti Jan 29 '15 at 16:08
  • 1
    Duplicate file voters. Look closely, I don't beleive this is a duplicate. – Elder Geek Jan 29 '15 at 17:57

How about

awk -F, 'NR==FNR {a[$1]=$0;next}; $1 in a {print a[$1]; print}' file1 file2
  • OK just be aware it won't necessarily do what you expect in the case where there are multiple instances of the same column1 value. – steeldriver Jan 29 '15 at 16:31

Maybe using uniq to first create the set of lines you want:

for pref in $(tail -q -n +2 *.txt | cut -d',' -f 1 | sort | uniq); do grep ^${pref}"," *.txt | cut -d':' -f 2 >> test.res; done


Create set of prefixes using uniq (skips first line of each file using tail):

for pref in $(tail -q -n +2 *.txt | cut -d',' -f 1 | sort | uniq)

For each prefix found, grep both files for lines starting with it, and remove grep "file matched" report using cut:

do grep ^${pref}"," *.txt | cut -d':' -f 2 >> test.res; done

Not the answer you're looking for? Browse other questions tagged or ask your own question.