← All cheatsheets

Shell

awk — column processing without writing a script

awk without writing a script: print columns, filter rows, combine filters with output, sum and count, and change field separators.

Print columns

awk '{print $1}' file — first whitespace-separated field

awk '{print $NF}' file — last field

awk -F, '{print $2}' file.csv — comma-separated

awk -F'\t' '{print $3}' file.tsv — tab-separated

Filter rows

awk '$3 > 100' file — rows where col 3 > 100

awk '/error/' log — rows matching /error/

awk 'NR>1' file — skip header (NR is row number)

awk 'NR==5' file — only row 5

Combine filter + print

awk -F, '$3 > 100 {print $1, $3}' file.csv — filtered, two columns

awk -F, 'NR>1 {print $2}' file.csv — skip header, print col 2

Aggregations

awk '{sum+=$1} END {print sum}' file — sum col 1

awk '{sum+=$1; n++} END {print sum/n}' file — mean col 1

awk '{print NR, $0}' file — add line numbers

Field count

awk '{print NF}' file — number of fields per line