how to sum each column in a file using bash

2019-02-26 09:56发布

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 have over 300 columns)

9,3,11,10,lable1 

how can I do that using bash. I tried using what described here but didn't work.

标签: bash shell awk
5条回答
Root(大扎)
2楼-- · 2019-02-26 10:17

Here's a Perl one-liner:

<file perl -lanF, -E 'for ( 0 .. $#F ) { $sums{ $_ } += $F[ $_ ]; } END { say join ",", map { $sums{ $_ } } sort keys %sums; }'

It will only do sums, so the first and last column in your example will be 0.

This version will follow your example output:

<file perl -lanF, -E 'for ( 1 .. $#F - 1 ) { $sums{ $_ } += $F[ $_ ]; } END { $sums{ $#F } = $F[ -1 ]; say join ",", map { $sums{ $_ } } sort keys %sums; }'
查看更多
3楼-- · 2019-02-26 10:17

Pure bash solution:

#!/usr/bin/bash


while IFS=, read -a arr
do
        for((i=1;i<${#arr[*]}-1;i++))
        do
                ((farr[$i]=${farr[$i]}+${arr[$i]}))
        done
        farr[$i]=${arr[$i]}
done < file
(IFS=,;echo "${farr[*]}")
查看更多
别忘想泡老子
4楼-- · 2019-02-26 10:22

Using awk:

$ awk -F, '{for (i=2;i<NF;i++)a[i]+=$i}END{for (i=2;i<NF;i++) printf a[i]",";print $NF}' file
9,3,11,10,lable1

This will print the sum of each column (from i=2 .. i=n-1) in a comma separated file followed the value of the last column from the last row (i.e. lable1).

查看更多
相关推荐>>
5楼-- · 2019-02-26 10:28

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; i<NF; i++) T[$NF,i]+=$i
  }
  END{
    for(i in L){
      s=i
      for(j=NF-1; j>1; 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<NF; i++) T[i]+=$i
  }
  END {
    labelsum()
  }
' file
查看更多
戒情不戒烟
6楼-- · 2019-02-26 10:28

A modified version based on the solution you linked:

#!/bin/bash

colnum=6
filename="temp"

for ((i=2;i<$colnum;++i))
do
  sum=$(cut -d ',' -f $i $filename | paste -sd+ | bc)
  echo -n $sum','
done
head -1 $filename | cut -d ',' -f $colnum
查看更多
登录 后发表回答