how to sum each column in a file using bash

前端 未结 5 1849
梦谈多话
梦谈多话 2021-01-22 14:19

I have a file on the following format

id_1,1,0,2,3,lable1
id_2,3,2,2,1,lable1
id_3,5,1,7,6,lable1

and I want the summation of each column ( I

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-22 15:07

    If the totals would need to be grouped by the label in the last column, you could try this:

    awk -F, '
      {
        L[$NF]
        for(i=2; i1; j--) s=T[i,j] FS s
          print s
        }
      }
    ' file
    

    If the labels in the last column are sorted then you could try without arrays and save memory:

    awk -F, '
      function labelsum(){
        s=p
        for(i=NF-1; i>1; i--) s=T[i] FS s
        print s
        split(x,T)
      }
      p!=$NF{
        if(p) labelsum()
        p=$NF
      }
      {
        for(i=2; i

提交回复
热议问题