Enric Agud Pique
Enric Agud Pique

Reputation: 1105

join two csv using key columns

I would like to join two files using the key column the name of the city. I want to join only the data of the cities that are repeated in both csv...

For example

File1.csv

London, 10,15
Rome, 12,18
Paris, 8, 16
Lissabon, 10,17

File2.csv

London, 11,16
Berlin, 13,19
Paris, 12,18
Lissabon, 11,19

Result I wish,

London,10,15,11,16 
Paris,8,16,12,18
Lissabon,10,17,11,19

How can I do it in bash?

Upvotes: 0

Views: 281

Answers (2)

anubhava
anubhava

Reputation: 785176

Using this awk:

awk -F, 'FNR==NR {a[$1]=$0;next} $1 in a{p=$1; sub(/^[^,]+, */, "");
         print a[p], $0}' OFS=, file1 file2
London, 10,15,11,16
Paris, 8, 16,12,18
Lissabon, 10,17,11,19

Upvotes: 1

chrisaycock
chrisaycock

Reputation: 37930

bash has a join command, though it requires that the input be sorted:

$ join -j 1 -t ',' <(sort File1.csv) <(sort File2.csv)
Lissabon, 10,17, 11,19
London, 10,15, 11,16
Paris, 8, 16, 12,18

Upvotes: 2

Related Questions