gpt4 book ai didi

linux - 合并两个文件添加列的值

转载 作者:太空宇宙 更新时间:2023-11-04 11:28:33 25 4
gpt4 key购买 nike

如何合并多个相同格式的文件,添加特定列的值,同时保持其他列不变?

如果我的文件的列的格式(有多行):

File 1:
a1 b1 c1 d1 e1

File 2:
a2 b2 c2 d2 e2

File n:
an bn cn dn en

where a1=a2=an, b1=b2=bn

Output:
a b (c1+c2+...cn) (d1+d2+...dn) (e1+e2+...en)

For example,

File 1:
1 0 200 5 50
2 1 345 9 22
3 2 287 4 33

File 2:
1 0 355 4 12
2 1 366 5 7
3 2 202 7 16

I want the Output:
1 0 555 9 62
2 1 711 14 29
3 2 489 11 49

最佳答案

awk-oneliner:

awk '{i=$1" "$2;a[i]+=$3;b[i]+=$4;c[i]+=$5}END{for(x in a)print x,a[x],b[x],c[x]}' file*

使用 3 个文件进行测试(oneliner 使用 n 个文件)

kent$  head file*
==> file1 <==
1 0 200 5 50
2 1 345 9 22
3 2 287 4 33

==> file2 <==
1 0 355 4 12
2 1 366 5 7
3 2 202 7 16

==> file3 <==
1 0 30 41 120
2 1 306 15 70
3 2 230 7 20

kent$ awk '{i=$1" "$2;a[i]+=$3;b[i]+=$4;c[i]+=$5}END{for(x in a)print x, a[x],b[x],c[x]}' file*
1 0 585 50 182
2 1 1017 29 99
3 2 719 18 69

关于linux - 合并两个文件添加列的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12860519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com