通过行名联接多个表 [英] Join multiple tables by row names

查看:62
本文介绍了通过行名联接多个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按行名称合并多个表.这些表的行数不同,并且它们具有唯一的和共享的行,所有这些都应出现在输出中.如果可能的话,我想用awk解决问题,但其他解决方案也可以.

I would like to merge multiple tables by row names. The tables differ in the amount of rows and they have unique and shared rows, which should all appear in output. If possible I would like to solve the problem with awk, but I am also fine with other solutions.

table1.tab

table1.tab

a 5
b 5
d 9

table2.tab

table2.tab

a 1
b 2
c 8
e 11

我想要获取下表的输出:

The output I would like to obtain the following table:

table3.tab

table3.tab

a 5 1
b 5 2
d 9 0
c 0 8
e 0 11

我尝试使用join

join table1.tab table2.tab > table3.tab

但我明白了

table3.tab

table3.tab

a 5 1
b 5 2

cde不在输出中.

推荐答案

此awk oneliner应该适用于您的示例:

this awk oneliner should work for your example:

awk 'NR==FNR{a[$1]=$2;k[$1];next}{b[$1]=$2;k[$1]}
END{for(x in k)printf"%s %d %d\n",x,a[x],b[x]}' table1 table2

测试

kent$  head f1 f2
==> f1 <==
a 5
b 5
d 9

==> f2 <==
a 1
b 2
c 8
e 11

kent$  awk 'NR==FNR{a[$1]=$2;k[$1];next}{b[$1]=$2;k[$1]}END{for(x in k)printf"%s %d %d\n",x,a[x],b[x]}'  f1 f2
a 5 1
b 5 2
c 0 8
d 9 0
e 0 11

这篇关于通过行名联接多个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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