我有两个文件file1和file2(空格分隔),都包含2列。 file1的第1列和第2列是Id和weight(浮点值)。类似地,file2具有Id1和权重(浮点值)。使用shell命令,如何在file1中找到第2列中第2列最接近的2个不同元素,为file1中的第2列的每个条目添加,并在file1中追加column1的相应元素?
file1
1 10.0
2 12.1
3 5.2
4 13.0
file2的
15 11.1
10 12.3
17 2.1
12 15.5
11 7.0
预期o / p
1 15 10
2 10 15
3 11 17
4 10 15
答案 0 :(得分:0)
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
命令: 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
}
<强>输出强>
1 15 10
2 10 15
3 11 17
4 10 15