AWK Cheat Sheet

Here’s a cheat sheet for AWK, a powerful text processing and pattern matching language commonly used in Unix and Linux environments:

AWK Basics

AWK Syntax:

awk 'pattern { action }' filename

Print Whole Line:

awk '{ print }' filename

Print Specific Column:

awk '{ print $1 }' filename

Print Multiple Columns:

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

Print with Custom Delimiter:

awk -F',' '{ print $1 }' filename

AWK Patterns

Begin/End Patterns:

  • Execute actions at the beginning or end of file.
awk 'BEGIN { action } END { action }' filename

Numeric Comparison:

Print lines where the second column is greater than 10.

awk '$2 > 10 { print }' filename

String Comparison:

Print lines where the first column is equal to “apple”.

awk '$1 == "apple" { print }' filename

Regular Expression Matching:

Print lines where the second column starts with “A”.

awk '$2 ~ /^A/ { print }' filename

AWK Built-in Variables

NF (Number of Fields):

  • Print lines with more than 3 fields.
awk 'NF > 3 { print }' filename

NR (Record Number):

Print line numbers along with lines.

awk '{ print NR, $0 }' filename

FS (Field Separator):

Change field separator to “:”.

awk -F':' '{ print $1 }' filename

OFS (Output Field Separator):

Change output field separator to “|”.

awk 'BEGIN { OFS="|" } { print $1, $2 }' filename

AWK Control Structures

if Statement:

Print lines where the second column is greater than 10.

awk '{ if ($2 > 10) print }' filename

for Loop:

Print first two columns separated by “:”.

awk '{ for (i=1; i<=2; i++) printf("%s:", $i); print "" }' filename

while Loop:

Print lines where the first column is “apple” using a while loop.

awk '{ i=1; while (i <= NF) { if ($i == "apple") print; i++ } }' filename

This AWK cheat sheet covers basic usage and some advanced features. AWK is a versatile tool, and you can explore more features and options in the AWK User’s Guide.