|
|
There are two ways to run an awk program. First, you can
type the command line to execute the pattern-action statements on
the set of named input files:
awk 'pattern-action statements' optional_list_of_input_files
For example, enter the following:
awk '{ print $1, $2 }' file1 file2
This program prints the first and second fields of every line in file1 and file2.
When printed, items separated by a comma in the print statement are separated by the output field separator (by default, a single blank). Each line printed is terminated by the output record separator (by default, a newline).
If no fields are specified with a print command, print prints $0, the current record.
Notice that the pattern-action statements are enclosed in single quotes. This protects characters like $ from being interpreted by the shell and also allows the program to be longer than one line.
If no files are mentioned on the command line, awk reads
from the standard input. You can also specify that input comes from
the standard input by using the hyphen ( - ) as one of the input
files. For example, to read input first from file1 and
then from the standard input, enter the following:
awk '{ print $3, $4 }' file1 -
This arrangement is convenient when the awk program is
short. If the program is long, it is often more sensible to put it
into a separate file and use the -f option to fetch it, as
follows:
awk -f program_file optional_list_of_input_files
You create an awk program the same way that you create a
shell script; using a text editor such as vi. (Because
awk programs are not directly executed, there is no need
to set the executable permission bit on the file.) For example, the
following command line specifies to fetch and execute the file
myprogram on input from the file file1:
awk -f myprogram file1
In the remainder of this chapter, we only show awk programs, without the command line that invokes them. In an example, if no input is mentioned, the input is assumed to be the file countries.