从2个文件中减去列并输出到新文件 [英] subtract columns from 2 files and output to new files

查看:54
本文介绍了从2个文件中减去列并输出到新文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个以下格式的文件.

I have 2 files in below formats.

File1_Stored.txt
ABC:100, 83
ABC:84, 53
ABC:14, 1222

File2_Stored.txt
ABC:100 , 83
ABC:84 , 1553
ABC:524 , 2626

我正在尝试以以下格式获取第3个文件.因此,只要差异为0,就不应出现,但如果差异不为0,则应出现

I am trying to get the 3rd file in below format. So, whenever difference is 0 it shouldnt appear but if the diffence is not 0 then it should appear like

Value , File1 Value , File2 Value , Difference
----------------------------------------------
ABC:84,  53          ,1553         , -1500
ABC:14,  1222        , 0           , 1222
ABC:524, 0           ,2626         ,-2626

我尝试使用awk做到这一点,但失败了

I tried doing it using awk to get the difference but it failing

awk 'NR==FNR{A[$1]=$2;B[$1]=$2}{$2-=A[$1]}1' File1_Stored.txt  File2_Stored.txt 

任何帮助都非常有用.

此致

推荐答案

$ cat tst.awk
BEGIN {
    FS="[[:space:]]*,[[:space:]]*"
    OFS=","
    print "Value", "File1 Value", "File2 Value", "Difference"
}
NR==FNR {
    a[$1] = $2
    next
}
{
    diff = a[$1] - $2
    if ( diff != 0 ) {
        print $1, a[$1]+0, $2, diff
    }
    delete a[$1]
}
END {
    for (key in a) {
        print key, a[key], 0, 0
    }
}

$ awk -f tst.awk file1 file2
Value,File1 Value,File2 Value,Difference
ABC:84,53,1553,-1500
ABC:524,0,2626,-2626
ABC:14,1222,0,0

这篇关于从2个文件中减去列并输出到新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆