Chapter 13. Practical awk Programs

Chapter 12 presents the idea that reading programs in a language contributes to learning that language. This chapter continues that theme, presenting a potpourri of awk programs for your reading enjoyment. There are three sections. The first describes how to run the programs presented in this chapter.

The second presents awk versions of several common POSIX utilities. These are programs that you are hopefully already familiar with, and therefore, whose problems are understood. By reimplementing these programs in awk, you can focus on the awk-related aspects of solving the programming problem.

The third is a grab bag of interesting programs. These solve a number of different data-manipulation and management problems. Many of the programs are short, which emphasizes awk’s ability to do a lot in just a few lines of code.

Many of these programs use the library functions presented in Chapter 12.

Running the Example Programs

To run a given program, you would typically do something like this:

awk -f program -- options 
                  files

Here, program is the name of the awk program (such as cut.awk), options are any command-line options for the program that start with a -, and files are the actual datafiles.

If your system supports the #! executable interpreter mechanism (see the Section 1.1.4 in Chapter 1), you can instead run your program directly:

cut.awk -c1-8 myfiles > results

If your awk is not gawk, you may instead need to use this:

cut.awk -- -c1-8 ...

Get Effective awk Programming, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.