# Problem with AWK script

**URL:** <https://community.unix.com/t/problem-with-awk-script/239747>\
**Category:** Shell Programming and Scripting\
**Created:** [May 10, 2009, 11:06pm UTC](https://community.unix.com/t/problem-with-awk-script/239747 "2009-05-10T23:06:21Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![repinementer](https://community.unix.com/letter_avatar/repinementer/32/5_5575768a8748004e209b776fc1b2916d.png) [@repinementer](https://community.unix.com/u/repinementer)\
**Post date:** [May 10, 2009, 11:06pm UTC](https://community.unix.com/t/problem-with-awk-script/239747/1 "2009-05-10T23:06:21Z")

</div>

Help Please  
I have 2 files. each file contain 2 columns.1st file 1st column contain symbols (keys-a1..a22..a-x,a-y) and 1st file 2nd column contain values (any like 2344,434323). Secondfile also the same but the values are may be different or not and the symbols (keys) are same but may be repeating, more or less than than 1st file 1st column.

Finding closest values (I would like to sort the data and join the the same keys (Joint and sort commands are not just doing the job I want), Then loop through this data and use an associative array/hash/\<whatever\> to keep track of the minimum diff between 2nd and 3rd fields for the same key.)

Tyler created some useful scripts but just not enough for this job  
I'm inluding the scripts just to give some idea

> [@](#):
>
> sort -k1,1 ip1 \> ip1\_sorted; sort -k1,1 ip2 \> ip2\_sorted

> [@](#):
>
> $ join ip1\_sorted ip2\_sorted |  
> \> awk '{  
> \> x = $2\>=$3 ? $2 - $3 : $3 - $2  
> \> if (mindiff[$1] == "") {mindiff[$1] = $1":"$2":"$3":"x}  
> \> else {split(mindiff[$1],arr,":"); diff = arr[4]  
> \> if (x \< diff) {mindiff[$1] = $1":"$2":"$3":"x}  
> \> }}  
> \> END {  
> \> for (i in mindiff){split(mindiff[i],arr,":"); print arr[1]" "arr[2]" "arr[3]}  
> \> }'

I'm inculding inputfiles just for clarification

$ sorted\_input1  
a1tab20  
a1tab30  
a1tab40  
a2tab20  
a2tab25  
a2tab67  
axtab45

$ sorted\_input2  
a1tab20  
a1tab45  
a2tab89  
axtab44  
axtab100  
axtab98

Output shouldbe

a1tab20tab20  
a1tab30tab20  
a1tab40tab45  
a2tab20tab89  
a2tab25tab89  
a2tab67tab89  
axtab45tab98
