user720491
user720491

Reputation: 599

Awk merging of two files on id

I would like to obtain the match the IDs of the first file to the IDs of the second file, so i get, for example, Thijs Al,NED19800616,39. I know this should be possible with AWK, but I'm not really good at it.

file1 (few entries)

NED19800616,Thijs Al
BEL19951212,Nicolas Cleppe
BEL19950419,Ben Boes
FRA19900221,Arnaud Jouffroy
...

file2 (many entries)

38,FRA19920611
39,NED19800616
40,BEL19931210
41,NED19751211
...

Upvotes: 1

Views: 171

Answers (2)

user000001
user000001

Reputation: 33387

With awk you can do

$ awk -F, 'NR==FNR{a[$2]=$1;next}{print $2, $1, a[$1] }' OFS=, file2 file1
Thijs Al,NED19800616,39
Nicolas Cleppe,BEL19951212,
Ben Boes,BEL19950419,
Arnaud Jouffroy,FRA19900221,

Upvotes: 3

William Pursell
William Pursell

Reputation: 212674

Don't use awk, use join. First make sure the input files are sorted:

sort -t, -k1,1 file1 > file1.sorted
sort -t, -k2,2 file2 > file2.sorted
join -t, -1 1 -2 2 file[12].sorted

Upvotes: 3

Related Questions