How awk works

Let's understand how the awk program processes every line. We will consider a simple file, sample.txt:

    $ cat sample.txt
    Happy Birth Day
    We should live every day.
  

Let's consider the following awk command:

    $ awk '{print $1, $3}' sample.txt
  

The following diagram shows how awk will process every line in memory:

An explanation of the preceding diagram is as follows:

  • awk reads a line from the file and puts it into an internal variable called $0. Each line is called a record. By default, every line is terminated by a new line.
  • Then, every record or line is divided into separate words or fields. Every word is stored in numbered ...

Get Learning Linux Shell Scripting - Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.