< Day Day Up > |
6.7. Patterns and Actions6.7.1 PatternsAwk patterns control what actions awk will take on a line of input. A pattern consists of a regular expression, an expression resulting in a true or false condition, or a combination of these. The default action is to print each line where the expression results in a true condition. When reading a pattern expression, there is an implied if statement. When an if is implied, there can be no curly braces surrounding it. When the if is explicit, it becomes an action statement and the syntax is different. (See "Conditional Statements" on page 227.) Example 6.19.% cat employees Tom Jones 4424 5/12/66 543354 Mary Adams 5346 11/4/63 28765 Sally Chang 1654 7/22/54 650000 Billy Black 1683 9/23/44 336500 (The Command Line) 1 nawk '/Tom/' employees Tom Jones 4424 5/12/66 543354 2 nawk '$3 < 4000' employees Sally Chang 1654 7/22/54 650000 Billy Black 1683 9/23/44 336500 EXPLANATION
6.7.2 ActionsActions are statements enclosed within curly braces and separated by semicolons.[2] If a pattern precedes an action, the pattern dictates when the action will be performed. Actions can be simple statements or complex groups of statements. Statements are separated by semicolons, or by a newline if placed on their own line.
FORMAT { action } Example 6.20.{ print $1, $2 } EXPLANATION The action is to print fields 1 and 2. Patterns can be associated with actions. Remember, actions are statements enclosed in curly braces. A pattern controls the action from the first open curly brace to the first closing curly brace. If an action follows a pattern, the first opening curly brace must be on the same line as the pattern. Patterns are never enclosed in curly braces. FORMAT pattern{ action statement; action statement; etc. } or pattern{ action statement action statement } Example 6.21.% nawk '/Tom/{print "Hello there, " $1}' employees Hello there, Tom EXPLANATION If the record contains the pattern Tom, the string Hello there, Tom will print. A pattern with no action displays all lines matching the pattern. String-matching patterns contain regular expressions enclosed in forward slashes. |
< Day Day Up > |