Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Chapter 6. The GNU awk programming language<br />
In this chapter we will discuss:<br />
♦ What is gawk?<br />
♦ Using gawk commands on the command line<br />
♦ How to format text with gawk<br />
♦ How gawk uses regular expressions<br />
♦ Gawk in scripts<br />
♦ Gawk and variables<br />
To make it more fun<br />
As with sed, entire books have been written about various versions of awk. This<br />
introduction is far from complete and is only intended for understanding examples in the<br />
following chapters. For more information, best start with the documentation that comes<br />
with GNU awk: "GAWK: Effective AWK Programming: A User's <strong>Guide</strong> for GNU<br />
Awk".<br />
6.1. Getting started with gawk<br />
6.1.1. What is gawk?<br />
Gawk is the GNU version of the commonly available UNIX awk program, another popular stream editor.<br />
Since the awk program is often just a link to gawk, we will refer to it as awk.<br />
The basic function of awk is to search files for lines or other text units containing one or more patterns. When<br />
a line matches one of the patterns, special actions are performed on that line.<br />
Programs in awk are different from programs in most other languages, because awk programs are<br />
"data-driven": you describe the data you want to work with and then what to do when you find it. Most other<br />
languages are "procedural." You have to describe, in great detail, every step the program is to take. When<br />
working with procedural languages, it is usually much harder to clearly describe the data your program will<br />
process. For this reason, awk programs are often refreshingly easy to read and write.<br />
What does it really mean?<br />
Back in the 1970s, three programmers got together to create this language. Their names were Aho,<br />
Kernighan and Weinberger. They took the first character of each of their names and put them together.<br />
So the name of the language might just as well have been "wak".<br />
6.1.2. Gawk commands<br />
When you run awk, you specify an awk program that tells awk what to do. The program consists of a series<br />
of rules. (It may also contain function definitions, loops, conditions and other programming constructs,<br />
advanced features that we will ignore for now.) Each rule specifies one pattern to search for and one action to<br />
perform upon finding the pattern.<br />
Chapter 6. The GNU awk programming language 69