A small language inside one command
awk reads input line by line and runs a program. The program is a sequence of pattern { action } rules. The pattern decides which lines fire the action; the action is anything you can write in awk's C-like mini-language.
Field variables
For each line, awk auto-splits on whitespace into $1, $2, ..., $NF (the last). NF is the number of fields, NR is the current line number. $0 is the whole line.
Examples that earn their keep
awk '{print $1}'— first field of each line.awk '{print $NF}'— last field.awk -F: '{print $1}' /etc/passwd— change delimiter to colon.awk '/error/ {print NR, $0}'— line number + content of lines containing "error".awk 'NR==5'— print only line 5.awk '{sum += $3} END {print sum}'— sum the third column.awk 'length($0) > 100'— show lines longer than 100 chars.
BEGIN and END blocks
BEGIN { ... } runs once before any input. END { ... } runs once after. Useful for headers, totals, averages.
awk 'BEGIN {print "size,name"} {print $5","$9}' <(ls -l)That's a CSV header plus size+name per file — pipeable into sort or jq.
Why awk over sed
sed is great for substitution. awk is great for arithmetic and field manipulation. Anytime you find yourself counting cells, summing columns, or filtering by numeric comparison, switch from sed to awk.