Skip to main content
In this guide, you’ll learn how to leverage awk’s built-in variables to parse and manipulate text data efficiently. We’ll cover:
  • Positional variables ($1, $2, …)
  • NR (Number of Records)
  • NF (Number of Fields)
  • $NF (Last Field in the Current Record)
  • FILENAME
Throughout this article, we’ll use a sample file, size.txt, generated from df -h:

1. Positional Variables

By default, awk splits each input line on whitespace. You can print specific fields using $1, $2, $3, and so on:
  • $1 → first column
  • $2 → second column
  • $3 → third column
For example, given abc.txt:

2. NR: Number of Records

NR tracks the current record (line) number. This is useful for adding line numbers or filtering specific lines:
Produces:
To print only the 8th line’s available space:

3. NF: Number of Fields

NF contains how many fields are in the current record. It helps you spot inconsistencies in your data:
The header line has 7 fields because “Mounted on” is split into two separate fields.

4. Combining NR and NF

Print both the record number and its field count:
Concatenate text with values:

5. $NF: The Last Field

Use $NF to refer directly to the last field of each record:

6. FILENAME: Current Filename

FILENAME holds the name of the file being processed (empty when reading from stdin):
When you pipe data into awk, FILENAME is empty:

7. Summary Table of Built-in Variables


8. Custom Field Separators

If your data uses a delimiter other than whitespace, set the -F option:
Always quote the -F argument when it contains special characters, e.g., awk -F'|' '...' file.txt.

Watch Video