我有以下格式的2个文件。
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那么它应该看起来像
Value , File1 Value , File2 Value , Difference
----------------------------------------------
ABC:84, 53 ,1553 , -1500
ABC:14, 1222 , 0 , 1222
ABC:524, 0 ,2626 ,-2626
我尝试使用awk来实现它,但它失败了
awk 'NR==FNR{A[$1]=$2;B[$1]=$2}{$2-=A[$1]}1' File1_Stored.txt File2_Stored.txt
任何帮助都很受欢迎。
此致
答案 0 :(得分:1)
$ 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
答案 1 :(得分:1)
awk 解决方案:
awk -F' *, *' 'BEGIN{ fmt="%s, %d, %d, %d\n" } # output format
NR==FNR{ a[$1]=$2; next }
{
d=a[$1]-$2; # difference
if ($1 in a && d==0) { delete a[$1]; next };
printf fmt, $1,a[$1]+0,$2,a[$1]-$2; delete a[$1]
}
END{
for(i in a) printf fmt, i,a[i],0,a[i]; # check for unmatched items
}' file1 file2
输出:
ABC:84, 53, 1553, -1500
ABC:524, 0, 2626, -2626
ABC:14, 1222, 0, 1222
答案 2 :(得分:1)
awk
脚本:
$ cat file.awk
BEGIN { FS=" *, *" }
NR==FNR { A[$1]=$2 ; B[$1]=0 ; next }
{ A[$1]=A[$1]+0 ; B[$1]=$2 }
END {
for (x in A)
{ diff=A[x]-B[x]
if (diff!=0) { printf "%s,%s,%s,%s\n",x,A[x],B[x],diff }
}
}
BEGIN { FS=" *, *" }
:将输入字段分隔符定义为a)零个或多个空格加上b)逗号加c)零个或多个空格NR==FNR
:对于第一个文件...... A[$1]=$2
:将值存储在数组A
和... B[$1]=0
:将B
数组{ A[$1]=A[$1]+0...
:对于第二个文件,将0添加到关联的A
数组(如果它不存在,则会产生新的A
数组项的效果),然后将当前记录值存储在数组B
END {...}
:处理完输入文件后...... for (x in A)
:循环遍历数组A
diff=...
:找到相应数组值之间的差异if (diff!=0) ...
:如果我们的差异不为零则打印结果脚本在行动:
$ awk -f file.awk File1_Stored.txt File2_Stored.txt
ABC:524,0,2626,-2626
ABC:14,1222,0,1222
ABC:84,53,1553,-1500