1

我想问一下如何用awk比较和计算2个文件之间的差异

文件1.txt

orange 30  
banana 25  
apple 30  
pear 35 

文件2.txt

orange 25  
apple 32  
jackfruit 15  
pear 40  
pineapple 20 

输出应该是两者之间的差异(和绝对值)并存储在

文件 3.txt:

orange 5  
banana 25  
apple 2  
pear 5  
jackfruit 15  
pineapple 20

有任何想法吗?

4

3 回答 3

2

一种方法:

$ awk '{x=a[$1]-$2;a[$1]=(x<0.0)?-x:x}END{for(k in a)print k,a[k]}' file1 file2
orange 5
jackfruit 15
apple 2
pineapple 20
pear 5
banana 25
于 2013-04-22T17:33:26.393 回答
2

这个单线应该工作:

 awk '$1 in a{a[$1]=sqrt((a[$1]-$2)^2);next}{a[$1]=$2}END{for(x in a)print x, a[x]}' file1 file2 

用你的例子:

kent$  head file1 file2
==> file1 <==
orange 30  
banana 25  
apple 30  
pear 35

==> file2 <==
orange 25  
apple 32  
jackfruit 15  
pear 40  
pineapple 20 

kent$  awk '$1 in a{a[$1]=sqrt((a[$1]-$2)^2);next}{a[$1]=$2}END{for(x in a)print x, a[x]}' file1 file2
orange 5
jackfruit 15
apple 2
pineapple 20
pear 5
banana 25
于 2013-04-22T16:29:56.873 回答
0
awk '{ if (a[$1] == "")
         a[$1] = $2;
       else
       {
         if ((a[$1] - $2) < 0)
        a[$1] = $2 - a[$1];
         else
        a[$1] = a[$1] - $2;
       }
    } END { for (e in a) { print e, a[e] }}' file1.txt file2.txt
于 2013-04-22T16:34:35.670 回答