Back to the command reference

awk

ShellAdvanced In simulator In real Linux

Pattern scanning and processing language

Name: awk: the initials of its authors Aho, Weinberger and Kernighan

You can practise it right away in the simulator, and use it in real Linux mode too.

Description

awk is a small programming language for text. It reads input line by line, splits each line into fields $1, $2 … on whitespace (or the -F separator), and runs an action for lines matching a pattern: pattern { action }.

It has variables, arithmetic, conditions, loops, arrays and BEGIN/END blocks, which makes it ideal for filtering columns, totals and reports. Systems usually ship GNU awk (gawk) or mawk.

Syntax

awk [OPTION]... 'PROGRAM' [FILE]...

Common options

-F FSField separator, e.g. -F,
-v VAR=VALUEPass a variable, e.g. -v n=3
-f FILERead the awk program from FILE
$1 $NFField 1, the last field; $0 is the whole line
NRCurrent line number
NFThe number of fields on the line ($NF is the last one)
/re/ { … }Only for lines matching re, e.g. awk '/ERROR/ {print $2}'
BEGIN { … } / END { … }Run once before the first line / after the last (to set up, or print totals)
FS / OFSInput / output field separators, e.g. BEGIN {FS=":"; OFS="\t"}

Examples

  • $ awk '{print $1}' access.log

    Print the first field of each line

    Explain
  • $ awk -F, '$3 > 80 {print $1}' scores.csv

    People who scored over 80

    Explain
  • $ awk '{sum += $2} END {print sum}' sales.txt

    Sum the second column

    Explain

Related