3

I am attempting to use AWK to compare two csv files and generate a merged output based on the compare results. Both files have a matched value and I can get it to display the desired value in data2 column ($2) with the match value (data1-$1 data2-$4) but what I want is data2-$2 and data1-$2. Looking to understand how to make that happen.

data1.csv

dt-101,willow
dt-102,dogwood
dt-103b,redbud
dt-103a,plum
dt-104,cedar
ls-47,oak
ls-47a,pinoak
ls-47b,liveoak

data2.csv

4001,00:00:00:01,eric,dt-101
4002,00:00:00:02,paul,dt-101
4003,00:00:00:03,steve,dt-103b
4004,00:00:00:04,mike,dt-104
4005,00:00:00:05,dave,ls-47b
4006,00:00:00:06,alex,dt-102
4007,00:00:00:07,adam,ls-47a

Here is the string i am using

awk -F, -v OFS=, 'NR==FNR{a[$1]; next} {print $2,a[$4]}' data1.csv data2.csv

Here is what I get

00:00:00:01,dt-101
00:00:00:02,dt-101
00:00:00:03,dt-103b
00:00:00:04,dt-104
00:00:00:05,ls-47b
00:00:00:06,dt-102
00:00:00:07,ls-47a

But what I want is

00:00:00:01,willow
00:00:00:02,willow
00:00:00:03,redbud
00:00:00:04,cedar
00:00:00:05,liveoak
00:00:00:06,dogwood
00:00:00:07,pinoak
  • 3
    Not sure how you are getting the stated output (since you don't seem to be assigning any values to the array elements) - it looks like you just need to assign a[$1]=$2 i.e. awk -F, -v OFS=, 'NR==FNR{a[$1]=$2; next} {print $2,a[$4]}' data1.csv data2.csv – steeldriver Mar 9 '17 at 17:52
  • Ah I had a[$1] = $1, missed that above some how. Changing to $2 fixed it thank you! – cw2 Mar 9 '17 at 18:29
2
$ awk -F, -v OFS=, 'NR==FNR{a[$1]=$2; next} {print $2,a[$4]}' data1.csv data2.csv

#Output

[GC@GC awk]$ ls
data1.csv  data2.csv
[GC@GC awk]$ awk -F, -v OFS=, 'NR==FNR{a[$1]=$2; next} {print $2,a[$4]}' data1.csv data2.csv
00:00:00:01,willow
00:00:00:02,willow
00:00:00:03,redbud
00:00:00:04,cedar
00:00:00:05,liveoak
00:00:00:06,dogwood
00:00:00:07,pinoak
[GC@GC awk]$ 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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