< Day Day Up > |
The conditional statements in awk were borrowed from the C language. They are used to control the flow of the program in making decisions. 6.17.1 if StatementsStatements beginning with the if construct are action statements. With conditional patterns , the if is implied ; with a conditional action statement, the if is explicitly stated, and followed by an expression enclosed in parentheses. If the expression evaluates true (nonzero or non-null), the statement or block of statements following the expression is executed. If there is more than one statement following the conditional expression, the statements are separated either by semicolons or a newline, and the group of statements must be enclosed in curly braces so that the statements are executed as a block. FORMAT if (expression) { statement; statement; ... } Example 6.127.1 % nawk '{if ( > 50 ) print "Too high"}' filename 2 % nawk '{if ( > 20 && <= 50){safe++; print "OK"}}' filename EXPLANATION
6.17.2 if/else StatementsThe if/else statement allows a two-way decision. If the expression after the if keyword is true, the block of statements associated with that expression are executed. If the first expression evaluates to false or 0, the block of statements after the else keyword is executed. If multiple statements are to be included with the if or else , they must be blocked with curly braces. FORMAT {if (expression) { statement; statement; ... } else{ statement; statement; ... } } Example 6.128.1 % nawk '{if( > 50) print " Too high" ;\ else print "Range is OK"}' filename 2 % nawk '{if ( > 50 ) { count++; print } \ else { x+5; print } }' filename EXPLANATION
6.17.3 if/else and else if StatementsThe if/else and else if statements allow a multiway decision. If the expression following the keyword if is true, the block of statements associated with that expression is executed and control starts again after the last closing curly brace associated with the final else . Otherwise, control goes to the else if and that expression is tested. When the first else if condition is true, the statements following the expression are executed. If none of the conditional expressions test true, control goes to the else statements. The else is called the default action because if none of the other statements are true, the else block is executed. FORMAT {if (expression) { statement; statement; ... } else if (expression){ statement; statement; ... } else if (expression){ statement; statement; ... } else{ statement } } Example 6.129.(In the Script) 1 {if ( > 89 && < 101 ) Agrade++ 2 else if ( > 79 ) Bgrade++ 3 else if ( > 69 ) Cgrade++ 4 else if ( > 59 ) Dgrade++ 5 else Fgrade++ } END{print "The number of failures is" Fgrade } EXPLANATION
|
< Day Day Up > |