Linux Shell Scripting Tutorial (LSST) v1.05r3 | ||
Chapter 7: awk Revisited | ||
|
Statement(s) are executed repeatedly UNTIL the condition is true. BEFORE the first iteration, expr1 is evaluated. This is usually used to initialize variables for the loop. AFTER each iteration of the loop, expr2 is evaluated. This is usually used to increment a loop counter.
Example:
|
Run it as follows:
$ awk -f while01.awk
Press ENTER to continue with for loop example from LSST v1.05r3
Sum for 1 to 10 numbers = 55
Goodbuy
Above for loops prints the sum of all numbers between 1 to 10, it does use very simple for loop to achieve this. It take number from 1 to 10 using i variable and add it to sum variable as sum = previous sum + current number (i.e. i).
Consider the one more example of for loop:
$ cat > for_loop |
Run it as (and give input as Welcome to Linux!)
$ awk -f for_loop
To test for loop
Press CTRL + C to Stop
Welcome to Linux!
Welcome vivek, 0 times.
Welcome vivek, 1 times.
Welcome vivek, 2 times.
Program uses for loop as follows:
for(i=0;i<NF;i++) | Set the value of i to 0 (Zero); Continue as long as value of i is less than NF (Remember NF is built in variable, which mean Number of Fields in record); increment i by 1 (i++) |
printf "Welcome %s, %d times.\n" ,ENVIRON["USER"], i | Print "Welcome...." message, with user name who is currently log on and value of i. |
You can use while loop as follows:
Syntax:
while (condition)
{
statement1
statement2
statementN
Continue as long as given condition is TRUE
}
While loop will continue as long as given condition is TRUE. To understand the while loop lets write one more awk script:
$ cat > while_loop |
Run it as
$awk -f while_loop
654
456
Next number please(CTRL+D to stop):587
785
Next number please(CTRL+D to stop):
Here user enters the number 654 which is printed in reverse order i.e. 456. Above program can be explained as follows:
no = $1 | Set the first fields ($1) value to no. |
remn = 0 | Set remn variable to zero |
{ | Start the while loop |
while (no > 1) | Continue the loop as long as value of no is greater than one |
remn = no % 10 | Find the remainder of no variable, and assign result to remn variable. |
no /= 10 | Divide the no by 10 and store result to no variable. |
print "%d", remn | Print the remn (remainder) variables value. |
} | End of while loop, since condition (no>1) is not true i.e false condition.. |
printf "\nNext number please (CTRL+D to stop):"; | Prompt for next number |
| ||
if condition in awk | Real life example in awk |