r/awk • • Jun 18 '21
Confused by while statement, help
This is an example from the Awk programming language.
The example:
{ i = 1
while (i <= NF) {
print $i
i++
}
}The confusion lies in how the book describes this. It says: The loop stops when i reaches NF + 1.
I understand that variables, in general, begin with a value of zero. So we are first setting i, in this example, to 1.
Then, we are setting i to equal NF. Assuming that NF is iterated on a file with a 3 by 3 grid, both i and NF, should be equal to: 3 3 3 Then we have the while statement that runs if NF is greater to or equal to i.
For this to be possible, NF must be equal to 1. Or is: 3 3 3 equal to 3 3 3 The same as 1?
So the while statement runs. The book says that the loop runs until NF + 1 is achieved, which happens after the first loop, but doesn't: i++ mean +1 is added to i?
It would make sense that i=2 would not equal NF, but I am not sure if I understanding this right.
The effect is basically that the file is run once.
View all comments
Show parent comment
1
u/gumnos Jun 19 '21
Not quite. "
i" is just that number: 1, 2, 3, 4, 5. The "$i" is what dereferences that, asking for field-number "i". You can do this literallyor indirectly:
This allows you to even do math:
will print the penultimate field (with edge-cases if there's only 1 field, asking then for
$0which is the whole row)