2

Quick question: I have to write a simple script and part of it is adding up every value in a column -> sum of every column and everything. So file

1 2 5
1 2
1

should return

column1: 3
column2: 4
column3: 5
sum: 12

My code is almost perfect but columns are not displayed in ascending order

if [[ $# -eq 0 ]]; then
  awk  '{ for (i=1;i<=NF;i++) sum[i]+=$i }; END { for (i in sum) print "column "i" : " sum[i];}' file.txt
  awk '{for(i=1;i<=NF;i++) sum+=$i;}; END {print "sum: " sum}' file.txt
fi

And the output is:

➜  script ./sum.sh
column 2 : 4
column 3 : 5
column 1 : 3
sum: 12

Why does it start with column 2?

2

for (variable in array) shall iterate, assigning each index of array to variable in an unspecified order.

Solution

if [[ $# -eq 0 ]]; then
    awk '(NF>m){m=NF}{for(i=1;i<=NF;i++)sum[i]+=$i}END{for(i=1;i<=m;i++)print("column "i" : "sum[i])}' file.txt
    awk '{for(i=1;i<=NF;i++)sum+=$i}END{print("sum: "sum)}' file.txt
fi

Output

column 1 : 3
column 2 : 4
column 3 : 5
sum: 12
|improve this answer|||||
  • So how to make it column1, column2, column3? – mikro098 Dec 15 '16 at 17:27
  • @codddeer123 See updated. – Cyker Dec 15 '16 at 17:32
  • Thanks, it works. I don't think that I would come up with this idea – mikro098 Dec 15 '16 at 18:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.