Getting Started with AWK: Basic Syntax and Structure

October 4, 2024

Getting Started with AWK: Basic Syntax and Structure

Welcome back to our AWK series! In this post, we will cover the basic syntax and structure of AWK programs. You’ll learn about the general format of an AWK command and how to execute simple scripts from the command line.

Understanding AWK Syntax

AWK is a powerful text processing tool that operates on a line-by-line basis. The general syntax of an AWK command is as follows:

awk 'pattern { action }' input-file

In this syntax:

  • pattern: This specifies the condition that must be met for the action to be executed. It can be a regular expression, a comparison, or even a built-in condition like NR (number of records).
  • action: This is the command or series of commands that will be executed when the pattern matches. Actions are enclosed in curly braces.
  • input-file: This is the file that AWK will process. If no file is specified, AWK will read from standard input (stdin).

Executing AWK from the Command Line

To execute an AWK command from the command line, simply type awk followed by the pattern and action. Here are a few examples:

Example 1: Print All Lines

To print all lines from a file named data.txt, you can use the following command:

awk '{ print }' data.txt

Example 2: Print Specific Columns

If you want to print only the first and third columns of a space-separated file, you can do so like this:

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

Example 3: Using Patterns

AWK can also filter lines based on specific patterns. For example, to print lines that contain the word