简体   繁体   中英

compare two columns in awk and print values from lookup files into output file

I have two files with first file having ~16000 files and the second file is lookup file having ~4000 lines.

Sample contents of file1 is given below:

id,title,name,value,details
01,23456,   ,   ,abcdefg
02,23456,   ,   ,abcdefg
03,12345,   ,   ,abcdefg
04,34534,   ,   ,abcdefg
...

Sample contents of lookup file file2 is given below:

sno,title,name,value
1,23456,abc,xyz
2,12345,cde,efg
3,34534,543,234

Now my requirement is compare column 2 of file1 in the lookup file and insert the values of column3 and column4 from lookup file into new output file.

The output file should look like below:

id,title,name,value,details
01,23456,abc,xyz,abcdefg
02,23456,abc,xyz,abcdefg
03,12345,cde,efg,abcdefg
04,34534,543,234,abcdefg

I did try few iterations by looking at existing questions but didn't get the results I desired. Any solution with awk would be much helpful.

$ cat vino.awk
BEGIN { FS = OFS = "," }
NR==FNR { name[$2]=$3; value[$2]=$4; next }
{ print $1, $2, name[$2], value[$2], $5 }

$ cat file1
id,title,name,value,details
01,23456,   ,   ,abcdefg
02,23456,   ,   ,abcdefg
03,12345,   ,   ,abcdefg
04,34534,   ,   ,abcdefg

$ cat file2
sno,title,name,value
1,23456,abc,xyz
2,12345,cde,efg
3,34534,543,234

$ awk -f vino.awk file2 file1
id,title,name,value,details
01,23456,abc,xyz,abcdefg
02,23456,abc,xyz,abcdefg
03,12345,cde,efg,abcdefg
04,34534,543,234,abcdefg

Here's an awk oneliner:

awk -F, 'FNR==NR {n[$2]=$3;v[$2]=$4} FNR!=NR{OFS=","; print $1,$2,n[$2],v[$2],$5}' file2 file1

The idea is to process in two passes, first for file2 to store all of the names and values, then for file1, to print out each line including the collected names and values.

awk -F"," 'BEGIN{OFS=","} NR==FNR {a[$2]=$3","$4;next} {print $1,$2,a[$2],$5;}' file2 file1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM