【问题标题】:compare and compute every and the absolute difference of 2 files in awk比较和计算 awk 中 2 个文件的每个和绝对差异
【发布时间】:2013-04-22 16:19:01
【问题描述】:

我想问一下如何用awk

比较和计算2个文件之间的差异

file1.txt

orange 30  
banana 25  
apple 30  
pear 35 

file2.txt

orange 25  
apple 32  
jackfruit 15  
pear 40  
pineapple 20 

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

file3.txt:

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

有什么想法吗?

【问题讨论】:

    标签: awk compare set-difference


    【解决方案1】:

    这个单行应该可以工作:

     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
    

    【讨论】:

    • 平方和取平方根对于获得绝对值而不是数字的最佳方法来说是多余的。
    【解决方案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
    

    【讨论】:

    • @Nate 我很高兴。不要忘记通过单击旁边的勾号来接受此答案。这将表明问题已解决。
    【解决方案3】:
    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
    

    【讨论】:

      猜你喜欢
      • 2012-10-18
      • 2019-09-08
      • 1970-01-01
      • 2023-03-11
      • 2014-02-10
      • 2018-09-14
      • 2021-10-03
      • 1970-01-01
      • 2019-05-24
      相关资源
      最近更新 更多