1

I am putting together a (g)awk file script that loops through the numeric data provided from in an input file, and has to sum the values in each row. I am creating an array and adding the row sums to each array position. Below is my code. The logic seems ok, but the output is off:

for(i = 1; i <= NF; ++i){
   for(j = 1; j <= NR; ++j){
       row[i] += $j
   }
}

1 Answer 1

4

You cannot loop through the lines. The loop through lines is done implicitly done by awk while reading the file.

So you just need to update the values in an array for the current line:

awk '{for (i=1;i<=NF;i++) a[i]+=$i}' file

Then, you can print the summary within the END block.

See an example:

$ cat a
1 2 3 4 5
6 7 8 9 10
$ awk '{for (i=1;i<=NF;i++) a[i]+=$i} END {for (i in a) print i " -> " a[i]}' a
1 -> 7
2 -> 9
3 -> 11
4 -> 13
5 -> 15
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for reminding me. A follow up on you answer: your example indicates the way to obtain column totals. I still can't figure out how to sum ROWS correctly. I find I don't get the expected results when I use the record number value: {for(i = 1; i <=NR;++i) rows[i] += $i}, as I would have expected.
@user2781042 Not sure what you mean with "sum rows": sum all the elements in a row? If this is the case, something like awk '{sum=0; for (i=1;i<=NF;i++) sum+=$i; print sum}' file makes it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.