Skip to content

awk

15 commands

A pattern-scanning language for column-based text: extract fields, compute totals and reformat output.

  • text processing
  • columns

Install awk

sudo apt install gawk

Fields4

awk '{print $1}' <file>

Prints the first whitespace-separated field of each line — the client IP in a web log.

Link
awk '{print $1, $NF}' <file>

Prints the first and last field; NF is the number of fields.

Link
awk -F'<sep>' '{print lt;n>}' <file>

Sets a custom field separator — here, user names and login shells.

Link
awk -F, 'NR>1 {print $2}' <file>

Skips the header row (NR is the line number).

Link

Filtering5

awk '/<pattern>/' <file>

Prints lines matching a regex, like grep.

Link
awk 'lt;n> <op> <value>' <file>

Filters on a field value — here, requests that returned 404.

Link
awk -F: '$3 == 0' /etc/passwd

Finds every account with UID 0. Anything other than root is a red flag.

Link
awk -F: '$7 !~ /nologin|false/' /etc/passwd

Lists accounts that have a real login shell.

Link
awk 'length > <n>' <file>

Prints lines longer than n characters.

Link

Counting and summing4

awk '{sum += lt;n>} END {print sum}' <file>

Sums a column — here, total bytes sent.

Link
awk '{c[$1]++} END {for (k in c) print c[k], k}' <file> | sort -rn

Counts occurrences of each value — the top requesting IPs.

Link
awk 'END {print NR}' <file>

Counts lines, like wc -l.

Link
awk '!seen[$0]++' <file>

Removes duplicate lines while keeping the original order.

Link

Formatting2

awk '{printf "%-20s %s\n", $1, $2}' <file>

Formats output in aligned columns with printf.

Link
awk 'BEGIN {OFS=","} {$1=$1; print}' <file>

Converts whitespace-separated columns to CSV.

Link