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 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.