The for
Statement
The for
statement makes it more convenient to count iterations of a loop. The general form of the for
statement looks like this:
for (initialization; condition; increment) body
This statement starts by executing initialization. Then, as long as condition is true, it repeatedly executes body and then increment. Typically initialization sets a variable to either zero or one, increment adds 1 to it, and condition compares it against the desired number of iterations.
Here is an example of a for
statement:
awk '{ for (i = 1; i <= 3; i++) print $i }'
This prints the first three fields of each input record, one field per line.
In the for
statement, body stands for any statement, but initialization, condition and increment are just expressions. You cannot set more than one variable in the initialization part unless you use a multiple assignment statement such as x = y = 0
, which is possible only if all the initial values are equal. (But you can initialize additional variables by writing their assignments as separate statements preceding the for
loop.)
awk '{ for (i =j= 1; i <= 3; i++)
{if (j <2){
j++;
print $i
}
}'
The same is true of the increment part; to increment additional variables, you must write separate statements at the end of the loop. The C compound expression, using C's comma operator, would be useful in this context, but it is not supported in awk
.
Most often, increment is an increment expression, as in the example above. But this is not required; it can be any expression whatever. For example, this statement prints all the powers of 2 between 1 and 100:
for (i = 1; i <= 100; i *= 2) print i
Any of the three expressions in the parentheses following the for
may be omitted if there is nothing to be done there. Thus, `for (;x > 0;)' is equivalent to `while (x > 0)'. If the condition is omitted, it is treated as true, effectively yielding an infinite loop (i.e., a loop that will never terminate).
In most cases, a for
loop is an abbreviation for a while
loop, as shown here:
initialization while (condition) { body increment }
source:http://www.staff.science.uu.nl/~oostr102/docs/nawk/nawk_toc.html#TOC77
No comments:
Post a Comment