6.9. awk Commands in a Script File
When you have multiple awk pattern/action statements, it is often much easier to put the statements in a script. The script is a file containing awk comments and statements. If statements and actions are on the same line, they are separated by semicolons. If statements are on separate lines, semicolons are not necessary. If an action follows a pattern, the opening curly brace must be on the same line as the pattern. Comments are preceded by a pound (#) sign.
Example 6.29.
% cat employees
Tom Jones:4424:5/12/66:54335
Mary Adams:5346:11/4/63:28765
Billy Black:1683:9/23/44:336500
Sally Chang:1654:7/22/54:65000
Jose Tomas:1683:9/23/44:33650
(The Awk Script)
% cat info
1 # My first awk script by Jack Sprat
# Script name: info; Date: February 28, 2004
2 /Tom/{print "Tom's birthday is "$3}
3 /Mary/{print NR, $0}
4 /^Sally/{print "Hi Sally. " $1 " has a salary of $" $4 "."}
# End of info script
(The Command Line)
5 % nawk –F: –f info employees2
Tom's birthday is 5/12/66
2 Mary Adams:5346:11/4/63:28765
Hi Sally. Sally Chang has a salary of $65000.
EXPLANATION
If the regular expression Tom is matched against an input line, the string Tom's birthday is and the value of the third field ($3) are printed. If the regular expression Mary is matched against an input line, the action block prints NR, the number of the current record, and the record. If the regular expression Sally is found at the beginning of the input line, the string Hi Sally. is printed, followed by the value of the first field ($1), the string has a salary of $, and the value of the fourth field ($4). The nawk command is followed by the –F: option, specifying the colon to be the field separator. The –f option is followed by the name of the awk script. Awk will read instructions from the info file. The input file, employees2, is next.
|