如何参考另一个列中的匹配值从两个不同的文件中添加两个列? [英] How to add two columns from two different files with reference to matching values in another column?
问题描述
文件1:
1 0.3
2 0.1
3 0.4
4 0.8
文件2:
2 0.7
4 0.2
6 0.5
8 0.9
检查文件1和文件2中的字段1,我们看到字符串2和4是相同的.这些是我的参考行.对于这些参考行,我想在两个文件中添加字段2中的值.
Examining field 1 in both File 1 and File 2, we see the strings 2 and 4 are in common. These are my reference rows. For these reference rows, I would like to add the values from field 2 in both files.
换句话说
-
在文件1和文件2中搜索匹配$ 1中的字符串.在这种情况下,为2和4.
search File 1 and File 2 for matching strings in $1. In this case, 2 and 4.
$ 1 = 2,则$ 2 = 0.1 + 0.7 = 0.8
for $1 = 2, then $2 = 0.1 + 0.7 = 0.8
$ 1 = 4,则$ 2 = 0.8 + 0.2 = 1.0
for $1 = 4, then $2 = 0.8 + 0.2 = 1.0
文件3中所需的输出:
1 0.3
2 0.8
3 0.4
4 1.0
即,文件3 =文件1,但行2中文件1中的$ 1与文件2中的$ 1匹配的行除外.
Namely, File 3 = File 1, except the rows, where $1 in File 1 matches $1 in File 2, have been added together in $2.
摘要
我想要一个脚本,该脚本可以在两个文件之间的$ 1中搜索匹配项,然后在找到$ 1匹配项的地方打印$ 2(文件1)+ $ 2(文件2).输出为文件3,无论发生什么匹配,该文件都将使用新的总和值打印文件1.非常感谢您的协助!
I would like a script that can search for matches in $1 between two files, then print $2 (File 1) + $2 (File 2) wherever a $1 match is found. The output is File 3, which prints File 1 with the new summed values whereever matches occurred. Any assistance is much appreciated!
推荐答案
能否请您尝试以下操作(如果您对awk
没问题).
Could you please try following(if you are ok with awk
).
awk 'FNR==NR{a[$1]=$2;next} {$2=$1 in a?$2+a[$1]:$2} 1' Input_file2 Input_file1
如果要在输出中使用浮点数直到1点以及正确的制表符格式,请尝试执行以下操作.
In case you want to have floating point till 1 point along with proper tab format in output then try following.
awk 'FNR==NR{a[$1]=$2;next} $1 in a{$2=sprintf("%.01f",$2+a[$1])} 1' Input_file2 Input_file1 | column -t
或者根据Ed ir先生的评论,我们不需要检查$1 in a
,因此将其从代码中删除.
Or as per Ed sir's comment we need not to check $1 in a
so removing it from code.
awk 'FNR==NR{a[$1]=$2;next} {$2=sprintf("%.01f",$2+a[$1])} 1' Input_file2 Input_file1 | column -t
这篇关于如何参考另一个列中的匹配值从两个不同的文件中添加两个列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!