1

Consider this simple awk calculator program and its output

$ awk '{while (getline) {n=0;for(i=NF;i>0;i--)n+=$i; print "sum: " n;}}'
1 1
2 2
sum: 4
3 3
sum: 6

Note how the first input line 1 1 produces no sum. All successive lines work as expected. Why is no sum being printed for the first line of input?

4

The use of getline throws away the first line. Try instead:

awk '{n=0;for(i=NF;i>0;i--)n+=$i; print "sum: " n;}'

By its nature, awk will iterate over input lines implicitly. Consequently, the code n=0;for(i=NF;i>0;i--)n+=$i; print "sum: " n; will be run for every line of input. There is no need here to explicitly loop over the lines.

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.