HI friends,
I have two files.
File2 2nd column need to be compared with file1 3rd column.If ID match found, then save in different file as file1 data
followed by file2.
file1:
No;age;id;name
1;24;37h;name1
2;22;67e;name2
4;48;9r;name3
6;67;9i8;name4
file2:
exp;id;pos
23;9r;hr
15;67e;tec
Expected new file output:
No;age;id;name;exp;pos
4;28;9r;name3;23;hr
2;24;37h;name1;15;tec
Thanks in advance
vasanth
Try this,
awk -F";" 'NR==FNR{a[$2]=$1FS$3;next} a[$3]{print $0 FS a[$3]}' file2 file1 > outputfile
1 Like
awk -F";" 'NR==FNR{a[$2]=$1 OFS $3;next} a[$3]{print $0,a[$3]}' OFS=\; file2 file1
2 Likes
HI,
Its worked fine. Thanks...
Can u explain the code..
Vasanth
awk '
BEGIN{
FS=OFS=";" # declare input Field Separator and Output Field Separator variable and set the value to ;
}
NR==FNR{
a[$2]=$1 OFS $3 # store file2 information in array a indexed by key field 2 having the value of two fields(1 and 3) separated by OFS
}
$3 in a{ # process the second (or subsequent) files, in this case file1, If field 3 is found as indexes in array a
print $0,a[$3] # print the whole record ($0) of file1 follow by the index of array a having the key field 3 of file1
}
' file2 file1
Hi,
Code worked fine. Thanks for good explanation
But the order of the output file is not in the order of file2.
The code output was as per file1, i need as per file2 order.
Expected new file output:
No;age;id;name;exp;pos
4;48;9r;name3;23;hr
2;24;37h;name1;15;tec
Thanks
Vasanth
Hi,
awk -F";" 'NR==FNR{a[$3]=$0;next} a[$2]{print a[$2] FS $1 FS $3}' file1 file2
Hi,
Thanks for all your suggestion.
And the below executes and gives output only for 512 lines.
I am having files around 8000 lines.
Is anything i need to change in script .
Thank you,
K.Vasanth
Hi,
Thanks for the replies.
Few more doubts raised, like file1 col3, does not matches with file2 col2, then the output must contain file2 as output with blank columns .
Eg:
file1:
No;age;id;name
1;24;37h;name1
2;22;67e;name2
4;48;9r;name3
6;67;9i8;name4
file2:
exp;id;pos
23;9r;hr
15;67e;tec
16;u67;thi
18; ;iol
Expected new file output:
No;age;id;name;exp;pos
4;28;9r;name3;23;hr
2;24;37h;name1;15;tec
;16;u67; ; ;thi
;18; ; ; ;iol
Thanks
Vasanth
awk -F";" 'NR==FNR{a[$3]=$0;next}{if(a[$2]){print a[$2],$1,$3}else{print " ",$1,$2," "," ",$3}}' OFS=";" file1 file2