awk看到每列重复的第一个字段

时间:2015-11-04 10:05:19

标签: bash awk

我正在尝试使用awk命令在匹配第一个字段时添加两列作为键。 该文件可以包含32列甚至更多。 列“时间”已修复。

Ex 6列HDDx-U00:

    time,HDD0-U00,HDD1-U00,HDD2-U00,HDD0-U00,HDD1-U00,HDD2-U00
    2015/10/26 16:10,1,3,5,2,4,6
    2015/10/26 16:11,1,2,3,4,5,5
    2015/10/26 16:12,2,2,3,6,2,3
  ... more row  in the file...

计算: 行:2015/10/26 16:10:

HDD0-U00 作为第一个键:(1 + 2)

HDD1-U00 作为第二关键:(3 + 4)

HDD3-U00 为第3个键:(5 + 6)

最后,得到这个结果:

time,HDD0-U00,HDD1-U00,HDD2-U00
2015/10/26 16:10,3,7,11
2015/10/26 16:11,5,7,8
2015/10/26 16:12,8,4,6

我用awk尝试了这个:

awk -F, '{k=$3;seen[k];for(i=4;i<=NF;++i)sum[k,i]+=$i}' $file

非常感谢你的帮助。

2 个答案:

答案 0 :(得分:1)

$ cat file
"No.","time",HDD0-U00,HDD1-U00,HDD2-U00,HDD0-U00,HDD1-U00,HDD2-U00
1,"2015/10/26 16:10",1,3,5,1,3,5
2,"2015/10/26 16:11",1,3,3,1,3,5
3,"2015/10/26 16:12",1,3,5,1,3,5
4,"2015/10/26 16:13",1,3,5,1,3,5
5,"2015/10/26 16:14",1,3,5,1,3,5

$ awk '
    # Split $1, $2, $NF on ","
    BEGIN {
        FS=",";
    }
    # Read first line to understand the header
    NR==1 {
        for (i=1; i<=NF; i++) {
            head[i] = $i
        }
        for (i=1; i<=NF; i++) {
            sum[head[i]] = $i;
        }
        # Print header:
        printf("%s", sum[head[1]]);
        for(i=2; i <= length(sum); i++) {
            printf(",%s", sum[head[i]]);
        }
        printf("\n");
        # Skip the last part of the script:
        next;
    }
    # Read all other lines
    {
        printf("%s,%s", $1, $2);
        # Remember to clear sum for every line
        delete sum;
        # Add up all of the values
        for (i=3; i <= NF; i++){
            sum[head[i]] += $i;
        }
        for(i=1; i <= length(sum); i++) {
            printf(",%s", sum[head[i+2]]);
        }
        printf("\n");
    }
' file

答案 1 :(得分:1)

如果你的班次模式是常数

awk -F\, -v shift=3 ' NR>1{printf("%s,%s",$1,$2)
          for (i=shift;i<=(NF/shift)+shift;i++){printf(",%s",$i+$(i+shift))};print ""}' file

注意:这将处理header

结果:

1,"2015/10/26 16:10",2,6,10
2,"2015/10/26 16:11",2,6,10
3,"2015/10/26 16:12",2,6,10
4,"2015/10/26 16:13",2,6,10
5,"2015/10/26 16:14",2,6,10