Unexpected result from awk

Hello,

Giving those commands:

cat > myfile 
1 
2 
3 
^D 
cat myfile | awk '{ s=s+$1 ; print s}'

The output is:

1
3
6

It seems like this command iterates each time on a different row so $1 is the first field of each row.. But what caused it to refer to each row ?.
What I mean is, how it knows that for the second iteration for example, $1 should be the first field of the second row rather then the first field of the first row again ?

Great question...except that the inventors of awk should be the target audience of this query

Because:

  • that is the way awk is described to work,
  • there are no loops in your code to cause an input line in your file to be evaluated more than once,
  • if awk was designed to only process the 1st line in a file (instead of processing each line in a file), it wouldn't be able to process multi-million line input files,
  • et cetera.

What in the description of awk on your system made you think that awk should only process the first line in a file?

The main code loops over all rows.
Perhaps you want to sum up each row but print only once, at the END?

awk 'BEGIN { s=0 } { s=s+$1 } END { print s }'

Or, cast an empty s to a zero

awk '{ s=s+$1 } END { print s+0 }'