- Positional variables (
$1,$2, …) NR(Number of Records)NF(Number of Fields)$NF(Last Field in the Current Record)FILENAME
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
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:
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: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):
FILENAME is empty:
7. Summary Table of Built-in Variables
| Variable | Description | Example |
|---|---|---|
$1, $2 | Positional fields (first, second, etc.) | awk '{ print $2 }' file.txt |
NR | Current record (line) number | awk '{ print NR }' file.txt |
NF | Number of fields in the current record | awk '{ print NF }' file.txt |
$NF | The last field in the current record | awk '{ print $NF }' file.txt |
FILENAME | Name of the file being processed (or empty) | awk '{ print FILENAME }' file.txt |
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.