5.4. awk Commands from within a File

If awk commands are placed in a file, the -f option is used with the name of the awk file, followed by the name of the input file to be processed. A record is read into awk's buffer and each of the commands in the awk file are tested and executed for that record. After awk has finished with the first record, it is discarded and the next record is read into the buffer, and so on. If an action is not controlled by a pattern, the default behavior is to print the entire record. If a pattern does not have an action associated with it, the default is to print the record where the pattern matches an input line.

Example 5.13.
(The Database)
   $1     $2      $3     $4        $5
					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

   % cat awkfile
1  /^Mary/{print  "Hello  Mary!"}
2  {print $1, $2,  $3}

3  % awk -f awkfile employees
					Tom Jones 4424
					Hello Mary! 
					Mary Adams 5346
					Sally Chang 1654
					Billy Black 1683

4  % awk -W source '/^Sally/' -f awkfile employees
					Tom Jones 4424
					Hello Mary!
					Mary Adams 5346
					Sally Chang 1654 7/22/54 650000
					Sally Chang 1654
					Billy Black 1683
				

Explanation

  1. If the record begins with the regular expression Mary, the string "Hello Mary!" is printed. The action is controlled by the pattern preceding it. Fields are separated by white space.

  2. The first, second, and third field of each record are printed. The action occurs for each line because there is not a pattern controlling the action.

  3. Awk reads commands from the script, awkfile.

  4. When the -W option (specific to gawk) is followed by the argument, source, awk can intermix awk commands provided at the command line as well as those coming from a script file when the script file is preceded by the -f option. In this example, awk will search for Sally at the beginning of the line, and then get the rest of its commands from awkfile. The -W option is provided with Gnu awk, not UNIX versions of awk.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.183.210