Your approach does the job, but it is somehow overkill: you are counting the number of columns, then cat
ting the file and calling awk
, while awk
alone can do all of it:
awk -F"\t" '{for(i=1; i<=NF; i++) sum[i]+=$i} END {for (i in sum) print i, sum[i]}' file
This takes advantage of NF
that stores the number of fields a line has (which is what you were doing with count=$(grep -c $'\t' $1)
). Then, it is just a matter of looping through the fields and sum to every element on the array, where sum[i]
contains the sum for the column i
. Finally, it loops through the result and writes its values.
Why isn't your approach suming a given column? Because when you say:
for n in $(seq 1 $count) ;do
cat $FILE | awk '{sum+=$1} END{print "sum=",sum}'
done
You are always using $1
as the element to sum. Instead, you should pass the value $n
to awk by using something like:
awk -v col="$n" '{sum+=$col} END{print "sum=",sum}' $FILE # no need to cat $FILE