Sum of all rows of all columns - Bash
awk, bash
Solution
echo "1 4 7
2 5 8
3 6 9 " \
| awk '{for (i=1;i<=NF;i++){
sums[i]+=$i;maxi=i}
}
END{
for(i=1;i<=maxi;i++){
printf("%s ", sums[i])
}
print}'
output
6 15 24
My recollection is that you can't rely on `for (i in sums)` to produce the keys any particular order, but maybe this is "fixed" in newer versions of gawk.
In case you're using an old-line Unix awk, this solution will keep your output in the same column order, regardless of how "wide" your file is.
IHTH
Problem
I have a file like this ``` 1 4 7 ... 2 5 8 3 6 9 ``` And I would like to have as output ``` 6 15 24 ... ``` That is the sum of all the lines for all the columns. I know that to sum all the lines of a certain column (say column 1) you can do like this: ``` awk '{sum+=$1;}END{print $1}' infile > outfile ``` But I can't do it automatically for all the columns.