Dev Anand Dev Anand - 6 months ago 8
Bash Question

Using Shell Script, search 2 closest, element of 2nd column in file2 for every entry of 2nd column in file1 and append elements of column1 in file1

I have two files file1 and file2 (space separated), both contain 2 columns. Column 1 and column 2 of the file1 is Id and weight(float value). Similarly file2 has Id1 and weight(float value). Using shell command, how to find the 2 closest, distinct elements of 2nd column in file2 for every entry of 2nd column in file1 and append corresponding elements of column1 in file1 ?

Answer

cat file1

1 10.0
2 12.1
3 5.2
4 13.0

cat file2

15 11.1
10 12.3
17 2.1
12 15.5
11 7.0

command : awk -f script.awk file2 file1

script.awk

#! /bin/awk -f
function abs(val) {
    return val < 0 ? -val : val
}
ARGV[1] == FILENAME{
    a[$1] = $2;
}
ARGV[2] == FILENAME{
    inf = 2^16;;
    one=inf; diffOne=inf;
    two=inf; diffTwo=inf;
    for(i in a){
        new = abs($2 - a[i]);
        if(diffOne > new ||  diffTwo > new){
            if(diffTwo >= diffOne && diffOne > new ){
                two = one; diffTwo = diffOne;           
                one = i; diffOne = new;

            } else {
                two = i; diffTwo = new;
            }
        }
    }
    if(one == inf){
        one = ""    
    }
    if(two == inf){
        two = ""    
    }
    print $1,one,two        
}

output

1 15 10
2 10 15
3 11 17
4 10 15