gawk: While Statement
1
1 7.4.2 The 'while' Statement
1 ---------------------------
1
1 In programming, a "loop" is a part of a program that can be executed two
1 or more times in succession. The 'while' statement is the simplest
1 looping statement in 'awk'. It repeatedly executes a statement as long
1 as a condition is true. For example:
1
1 while (CONDITION)
1 BODY
1
1 BODY is a statement called the "body" of the loop, and CONDITION is an
1 expression that controls how long the loop keeps running. The first
1 thing the 'while' statement does is test the CONDITION. If the
1 CONDITION is true, it executes the statement BODY. (The CONDITION is
1 true when the value is not zero and not a null string.) After BODY has
1 been executed, CONDITION is tested again, and if it is still true, BODY
1 executes again. This process repeats until the CONDITION is no longer
1 true. If the CONDITION is initially false, the body of the loop never
1 executes and 'awk' continues with the statement following the loop.
1 This example prints the first three fields of each record, one per line:
1
1 awk '
1 {
1 i = 1
1 while (i <= 3) {
1 print $i
1 i++
1 }
1 }' inventory-shipped
1
1 The body of this loop is a compound statement enclosed in braces,
1 containing two statements. The loop works in the following manner:
1 first, the value of 'i' is set to one. Then, the 'while' statement
1 tests whether 'i' is less than or equal to three. This is true when 'i'
1 equals one, so the 'i'th field is printed. Then the 'i++' increments
1 the value of 'i' and the loop repeats. The loop terminates when 'i'
1 reaches four.
1
1 A newline is not required between the condition and the body;
1 however, using one makes the program clearer unless the body is a
1 compound statement or else is very simple. The newline after the open
1 brace that begins the compound statement is not required either, but the
1 program is harder to read without it.
1