Reputation: 691
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
}
}
Upvotes: 1
Views: 10731
Reputation: 289815
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
Upvotes: 4