1.1.3 Running Long Programs

Sometimes awk programs are very long. In these cases, it is more convenient to put the program into a separate file. In order to tell awk to use that file for its program, you type:

awk -f source-file input-file1 input-file2 ...

The -f instructs the awk utility to get the awk program from the file source-file (see Command-Line Options). Any file name can be used for source-file. For example, you could put the program:

BEGIN { print "Don't Panic!" }

into the file advice. Then this command:

awk -f advice

does the same thing as this one:

awk 'BEGIN { print "Don\47t Panic!" }'

This was explained earlier (see Running awk Without Input Files). Note that you don’t usually need single quotes around the file name that you specify with -f, because most file names don’t contain any of the shell’s special characters. (If your file names have spaces in them, then you will need the single quotes.) Notice that in advice, the awk program did not have single quotes around it. The quotes are only needed for programs that are provided on the awk command line. (Also, placing the program in a file allows us to use a literal single quote in the program text, instead of the magic ‘\47’.)

If you want to clearly identify an awk program file as such, you can add the extension .awk to the file name. This doesn’t affect the execution of the awk program but it does make “housekeeping” easier.