合并添加列值的两个文件

时间:2012-10-12 13:48:44

标签: linux join awk

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

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

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

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

$ awk '{getline x <f; split(x,a," ");$3+=a[3];$4+=a[4];$5+=a[5]}1' f="file1" file2
1 0 555 9 62
2 1 711 14 29
3 2 489 11 49

使用getline,您也可以并行读取另一行的内容。一旦我们分割了第二个文件内容,就可以总结出来。

答案 2 :(得分:0)

Guru提供的类似解决方案,但针对 n 文件进行了推广:

假设有以下输入文件:

==> 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 400 6 14
2 1 500 5 7
3 2 202 7 16

运行此awk脚本:

awk '
    FNR < NR { 
        exit; 
    } 
    {
        for ( i = ARGC - 1; ARGV[i] != FILENAME; i-- ) {
            getline line < ARGV[i];
            r = split( line, fields );
            if ( r < 3 ) {
                continue;
            }
            if ( $1 == fields[1] && $2 == fields[2] ) {
                for ( j = 3; j <= NF; j++ ) {
                    $j += fields[j];
                }
            }
        }
        print;
    }
' file[123]

产量:

1 0 955 15 76
2 1 1211 19 36
3 2 691 18 65
相关问题