awk

On this page 7

awk is a pattern-scanning and text-processing language that reads input line by line, splits each line into fields, and executes actions for every line that matches a given pattern. On Linux and other Unix-like systems it is a standard command-line tool, used in the shell and terminal to extract columns, filter records, compute totals and reformat output from logs, configuration files and other commands.

The name comes from the initials of its creators, Alfred Aho, Peter Weinberger and Brian Kernighan, who wrote it at Bell Labs in 1977. Unlike grep, which only selects lines, and sed, which mainly edits streams, awk is a complete programming language with variables, arithmetic, associative arrays and control flow.

How awk processes input

awk follows a simple pattern-action model: a program is a list of rules in the form pattern { action }, and awk applies every rule to every input record, which by default is one line. If the pattern matches, the action runs; if the pattern is omitted, the action runs for every record; if the action is omitted, the matching record is printed.

Each record is split into fields by the field separator, which by default is any run of spaces or tabs. The fields are available as $1, $2 and so on, while $0 holds the entire record. Two special patterns, BEGIN and END, run once before the first record and once after the last, which makes them the natural place for initialization and final reports.

The table below lists the built-in variables that control and describe this processing loop.

VariableMeaningTypical use
FSInput field separatorSet to a colon for /etc/passwd
OFSOutput field separatorProduce comma-separated output
RSInput record separatorProcess paragraph-based input
NRNumber of records read so farSkip a header with NR > 1
NFNumber of fields in the current recordPrint the last field with $NF
FNRRecord number within the current fileCompare two files in one pass
FILENAMEName of the current input fileLabel output by source file
Key built-in variables in awk

A one-line example shows the model: awk -F: '$3 >= 1000 { print $1 }' /etc/passwd sets the separator to a colon, tests the numeric user ID in field three, and prints the account name for every regular user.

Language features beyond simple filtering

awk supports typed-on-demand variables, so the same value is treated as a number or a string depending on context, without declarations. Variables start empty or zero, which allows compact idioms such as { sum += $5 } END { print sum } to total a column with no setup.

The most powerful feature is the associative array, indexed by arbitrary strings. The idiom { count[$1]++ } END { for (k in count) print k, count[k] } counts occurrences of each distinct value, which replaces a combination of sort and uniq and keeps the work in a single pass over the data.

awk also provides printf for formatted output, regular-expression matching with the ~ operator, string functions such as length, substr, split, sub and gsub, and arithmetic with double-precision floating point. User-defined functions, getline for reading extra input and output redirection to files or pipes complete the toolkit.

The following table groups commonly used functions by purpose.

FunctionCategoryEffect
length(s)StringReturns the number of characters
substr(s, i, n)StringExtracts n characters from position i
split(s, a, sep)StringSplits a string into an array
gsub(re, r)Regular expressionReplaces all matches in the record
match(s, re)Regular expressionSets RSTART and RLENGTH
int(x)NumericTruncates toward zero
sprintf(fmt, …)FormattingReturns a formatted string
Frequently used awk functions

Implementations and portability

The awk language is specified by POSIX, but several implementations exist with different extensions and performance. On most Linux distributions the awk command is a link to GNU awk (gawk) or to mawk, while BusyBox-based systems such as Alpine Linux ship a compact built-in version.

Scripts that must run everywhere should stay within the POSIX feature set. The table compares the implementations an administrator is most likely to meet.

ImplementationMain strengthsNotable limitations
gawkRich extensions, network and time functionsSlower than mawk on large inputs
mawkVery fast bytecode interpreterFewer extensions, older releases lag
The One True AWKReference version by the original authorsMinimal feature set
BusyBox awkTiny footprint for containersPartial compatibility in edge cases
Common awk implementations

Extensions such as gensub, strftime, true multidimensional arrays and the -i inplace option are specific to gawk. Using them in a script labeled as plain awk is a common source of failures when the script moves to another system.

Choosing between awk, grep, sed and other tools

awk is the right tool when the task depends on columns, calculations or state across lines. For pure line selection, grep is simpler and faster; for substitution in a stream, sed is more concise; and for complex logic, nested data or long-lived maintenance, a general-purpose language such as Python is easier to test and read.

The decision table below matches typical tasks to the most suitable tool.

TaskRecommended toolReason
Find lines containing an error codegrepFastest pure line filter
Replace a hostname in a filesedConcise in-place substitution
Sum bytes per client IP in a logawkFields plus associative arrays
Reorder and format columnsawkDirect field access and printf
Parse JSON outputjqUnderstands nested structure
Multi-step data pipelinePythonReadable, testable, extensible
Selecting a text-processing tool

Inside a pipe, awk often replaces several chained commands. Writing ps aux | awk '$3 > 10 { print $2, $11 }' filters and projects in one process, which is both faster and easier to audit than a chain of grep, cut and tr.

Pitfalls and common mistakes

The most frequent error is shell quoting. awk programs should be enclosed in single quotes so that the shell does not expand $1 as a positional parameter; shell values are passed in safely with -v name=value rather than by splicing them into the program text.

  • Default splitting collapses whitespace, so empty columns in fixed-width or tab-separated data shift field numbers; set -F'\t' explicitly for TSV.
  • CSV with quoted commas is not handled by a simple comma separator; gawk offers --csv in recent versions, otherwise use a dedicated parser.
  • String versus numeric comparison depends on context, so values such as 10 and 9 may compare as text unless forced with +0.
  • Locale settings affect character classes and speed; LC_ALL=C often accelerates processing of large ASCII logs considerably.
  • Floating-point precision limits exact integer arithmetic to about 2 to the 53rd power, which matters for byte counters on large systems.

Long awk programs written on one line become difficult to maintain. Once a script exceeds a few rules, it belongs in a separate file loaded with awk -f, with comments and meaningful variable names.

In plain words

Imagine a long printed table and a helper who reads it row by row. You tell the helper something like: whenever the third column is larger than 100, write down the name in the first column, and at the end tell me the total. That tireless row-by-row helper is awk.

It is built into almost every Linux system and works directly in the terminal. awk turns rows of text into columns you can test, count and rearrange, which makes it ideal for quick answers from logs and reports without opening a spreadsheet.

A real-world example

An operations engineer notices that a web server’s outbound traffic has doubled overnight and needs to know which clients are responsible. The access log has about 4 million lines, with the client IP address in the first field and the response size in bytes in the tenth.

The engineer runs awk '{ bytes[$1] += $10 } END { for (ip in bytes) print bytes[ip], ip }' access.log | sort -rn | head -5. In one pass, awk sums the bytes per IP address in an associative array, and the remaining commands sort the result and show the top five clients.

The command finishes in a few seconds and reveals that a single misconfigured backup job downloaded the same large archive repeatedly. After the job is corrected, traffic returns to its normal level, and the one-liner is saved as a small script for future incidents.