On this page 9 sections
Think in records and fields
awk processes input one record at a time. By default a record is one line and fields are separated by whitespace. $1 represents the first field, $2 the second and $0 the complete line.
awk '{print $1}' file.txtawk '{print $1, $3}' file.txtChoose a delimiter
-F sets the input field separator. This makes awk useful for colon-separated system files, CSV-like input and structured logs.
awk -F: '{print $1}' /etc/passwdawk -F: '{print $1, $7}' /etc/passwdFilter records
A condition placed before the action controls which lines are processed.
awk -F: '$3 == 0 {print $1}' /etc/passwdps aux | awk '$3 > 10 {print $2, $3, $11}'Pattern matching
awk supports regular expressions directly in conditions.
awk '/ERROR/ {print}' application.logawk '!/^#/ {print}' config.txtBuilt-in variables
NF is the number of fields on the current line and NR is the current record number. $NF therefore represents the last field.
awk '{print $NF}' file.txtawk '{print NR, $0}' file.txtawk '{print NF, $0}' file.txtBEGIN and END
BEGIN executes before any input is processed. END executes after all records have been processed. They are useful for headers, initialisation and final calculations.
awk 'END {print NR}' file.txtawk 'BEGIN {print "USER SHELL"} {print $1, $2}' file.txtCalculate totals
awk variables make it easy to aggregate numerical fields.
awk '{sum += $2} END {print sum}' values.txtawk '{sum += $2} END {if (NR) print sum/NR}' values.txtAnalyse web logs
For common web log formats, the first field often contains the client IP. awk can extract it before sort and uniq are used to count repeated clients.
awk '{print $1}' access.log | sort | uniq -c | sort -nr | headCustom output formatting
printf provides precise formatting compared with print.
awk -F: '{printf "%-20s %s\n", $1, $7}' /etc/passwd