AWK’s built-in variables hold information about the current input record, fields, input files, and output formatting. For example, NF gives the number of fields in the current record, NR counts records read, and FS sets the input field separator; these values let an AWK program inspect and format text without maintaining every detail itself.
What AWK Variables Represent
AWK reads input as a sequence of records, usually lines. It divides each record into fields, making the current record and its pieces available to your program. Built-in variables expose this processing state, and some can be assigned to change how AWK reads or prints data.
For example, with a file containing Rina 82, the default setup treats the line as one record with two fields. $0 is the whole line, $1 is Rina, $2 is 82, and NF is 2.
- Information variables, such as
NRandNF, report what AWK has read. - Control variables, such as
FSandOFS, affect input splitting or output joining. - Special values, such as
FILENAMEandSUBSEP, support file handling and less common operations.
Core Record and Field Variables
The most useful starting point is the relationship between $0, numbered fields, NF, and the record counters.
$0: the complete current record. By default, a record is a line.$1,$2, and so on: individual fields in that record. Field numbering starts at one.NF: the number of fields in the current record. It is zero for a record with no fields.NR: the total number of records read so far across all input files.FNR: the number of records read so far in the current input file. It starts over when AWK moves to another file.
This program prints each line number and its field count:
{ print NR, NF }
Given two input lines, red blue and green, it prints 1 2 and 2 1. With multiple files, use FNR when you want line numbering to restart per file; use NR for a continuous count.
Fields can also be changed. Assigning to $1, for example, changes that field and causes AWK to rebuild $0 using the output field separator. Assigning a new value to NF can remove fields by lowering the count or create empty fields by raising it. These operations affect the current record, not the original file on disk.
Separators and Output Formatting
FS is the input field separator; OFS is the output field separator. The default input behavior splits fields on runs of spaces and tabs, with leading and trailing whitespace handled as separators. The default output separator is a single space.
Set separators in a BEGIN block to make the choice clear before records are processed:
BEGIN { FS = ","; OFS = " | " }
{ print $1, $2 }
For comma-separated rows, this reads fields at commas and prints the first two with a vertical-bar separator. This simple approach is appropriate for uncomplicated data, but it is not a complete parser for CSV files that may contain quoted commas, escaped quotes, or embedded newlines.
RS controls the input record separator, which is normally a newline. ORS is the string AWK appends after each output record; it defaults to a newline. For example, ORS = ";\n" puts a semicolon after each printed record.
OFS and ORS affect output created with print. They do not automatically alter text produced with printf, where you specify the formatting yourself:
{ printf "%s: %s\n", $1, $2 }
Formatting and File-Related Variables
FILENAME: the name of the current input file. When input comes from standard input, its value is commonly-.ARGCandARGV: the count of command-line arguments and the argument array. AWK also uses arguments inname=valueform as variable assignments, so argument handling has details beyond an ordinary list of filenames.CONVFMT: the format used when a number is converted to a string in general expression contexts.OFMT: the format used byprintwhen it converts numbers for output. Its traditional default is%.6g.SUBSEP: a separator used internally when AWK represents a multidimensional array index as a combined key. It matters mainly when working with arrays indexed by multiple values.
Formatting behavior can vary in details between AWK implementations, especially for newer features and special variables. If a script depends on a particular implementation, check its documentation rather than assuming every extension is portable. Common implementations include traditional AWK, nawk, and GNU AWK (gawk).
A Practical Example: Summing a Column
Suppose a whitespace-delimited file has a name in its first field and a numeric value in its second. This program totals the second field and reports how many records it processed:
{ total += $2 }
END { printf "Records: %d\nTotal: %.2f\n", NR, total }
The action runs once for every record, adding $2 to total. The END block runs after input is finished. NR provides the record count, while printf displays the total to two decimal places. AWK initializes an unassigned variable such as total to a numeric zero when used in arithmetic.
To skip a header row, a pattern can test the record number: NR > 1 { total += $2 }. If multiple files are processed and each has its own header, test FNR > 1 instead. This is a practical example of choosing between the global and per-file counters.
Common Mistakes and Portability
- Confusing
NRandFNR: the first counts across the complete input stream; the second restarts for each file. - Assuming commas are parsed as full CSV: setting
FSto a comma does not handle every quoting rule. - Changing a separator too late: set
FSbefore the relevant records are read, commonly inBEGIN. Changing it does not retroactively split an already-read record. - Expecting
OFSto controlprintf: use explicit format strings and separators withprintf. - Assuming every special variable is universal: core variables are widely shared, but some behavior and additional variables differ among implementations.
AWK’s names are case-sensitive: NF and nf are different identifiers. Also, NR and FNR are not interchangeable when handling several files or resetting logic at file boundaries.
Frequently Asked Questions
What does NF mean in AWK?NF is the number of fields in the current record. It is often used to check whether a line has enough columns or to access the last field as $NF.
What is the difference between NR and FNR?NR counts records across all input files, while FNR counts records in the current file and resets when a new file begins.
How do I change the field separator in AWK?
Assign a value to FS, preferably in a BEGIN block. For example, BEGIN { FS = ":" } splits each record at colons.
Can I assign a value to NF?
Yes. Lowering NF removes fields from the current record; raising it adds fields. It changes AWK’s current record representation, not the source file.
What does $0 mean in AWK?$0 represents the complete current record. A numbered field such as $3 represents one field within that record.
Choosing the Right Variable
For routine text processing, start with $0, numbered fields, NF, and the separators FS and OFS. Add NR or FNR when records must be counted, and use FILENAME when output should identify its source. Understanding which values describe input and which control it makes AWK programs easier to read, debug, and adapt to new data.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.
More cards in this drawer
- Campus Tech Innovation Hubs: What They Are
- Poco C51 Airtel Prepaid Locked Variant India?
- Jenkins vs GitHub Actions: Which CI/CD Fits Your Team?
- Turn Off Backup Encryption in iTunes?
- Shared VPS Hosting: Is It Better?
- Disk Defrag Pro: What It Does and Whether You Need It