AWK Command Cheat Sheet

Basic Usage

awk '{print $1}' filename

Print the first column of each line in the file.

awk '{print $1, $3}' filename

Print the first and third columns of each line.

awk '/pattern/ {print $0}' filename

Print lines that match a pattern.

Common Options

awk -F":" '{print $1}' /etc/passwd - Use ":" as the field separator.

awk 'NR==3' filename - Print only the third line.

awk 'NR>=2 && NR<=4' filename - Print lines 2 through 4.

awk 'END {print NR}' filename - Print the total number of lines.

awk '{sum += $1} END {print sum}' filename - Sum all values in the first column.

Advanced Usage

awk '{if ($3 > 50) print $0}' filename - Print lines where the third column is greater than 50.

awk 'BEGIN {print "Header"} {print $1} END {print "Footer"}' filename - Print a header, each first column, and a footer.

awk 'BEGIN {OFS=" - "} {print $1, $2}' filename - Change the output field separator.

awk '{gsub("old", "new")} {print}' filename - Replace "old" with "new" in each line.

awk 'length($0) > 20' filename - Print only lines longer than 20 characters.