aquaabhi
aquaabhi

Reputation: 3

Merging of two csv files using awk based on common column

I have one file with 11 columns with first column as primary id - P1 second csv with three columns with first column as same primary id - P1, though not at same level in both files, I am merging both files using below command:

awk 'NR==FNR {h[$2] = $3; next} {print $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,h[$2]}' first.csv second.csv > final.csv

however, getting only three columns in new csv

Upvotes: 0

Views: 889

Answers (2)

user000001
user000001

Reputation: 33327

If first.csv has 11 columns and second.csv has three, then you have your files are in the wrong order. Try like this:

awk 'NR==FNR {h[$2] = $3; next} {print $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,h[$2]}' second.csv first.csv > final.csv

You are also not using the first column as keys in this example, but the second one.

Upvotes: 0

Thomas Baruchel
Thomas Baruchel

Reputation: 7517

You should see if join wouldn't be an easier solution. Type man join for that:

join - join lines of two files on a common field

Upvotes: 1

Related Questions