Skip to main content

๐Ÿง  AWK Command Cheatsheet

awk is a powerful text-processing tool in Unix/Linux, perfect for manipulating data in files or command output. It's often used for reporting, filtering, and transforming structured text.


๐Ÿ“ฆ What is AWK?โ€‹

  • Processes input line-by-line
  • Splits each line into fields using a delimiter
  • Executes actions based on optional patterns

Syntax:

bash snippet


๐Ÿ“ Basic Examplesโ€‹

๐Ÿ”น Print all linesโ€‹

bash snippet

๐Ÿ“ค Output:

๐Ÿ”น Print first columnโ€‹

bash snippet

๐Ÿ“ค Output:


๐Ÿ” Using Patternsโ€‹

๐Ÿ”น Match a specific stringโ€‹

bash snippet

โœ… Filters lines containing "error".

๐Ÿ”น Match column valueโ€‹

bash snippet

โœ… Prints lines where second column value is greater than 50.


๐Ÿ”ฃ Field & Line Handlingโ€‹

VariableDescription
$0Entire line
$1,$2Fields
NFNumber of fields in current line
NRCurrent line number
FSInput field separator
OFSOutput field separator

๐Ÿ”น Print number of fieldsโ€‹

bash snippet

๐Ÿ”น Print last fieldโ€‹

bash snippet


๐Ÿงฎ Calculationsโ€‹

๐Ÿ”น Sum a columnโ€‹

bash snippet

๐Ÿ“ค Output:

๐Ÿ”น Averageโ€‹

bash snippet

๐Ÿ“ค Output:


๐Ÿ“Œ Conditionalsโ€‹

๐Ÿ”น If-elseโ€‹

bash snippet

๐Ÿ“ค Output:


๐Ÿ”ƒ With Delimitersโ€‹

๐Ÿ”น Set delimiter (CSV)โ€‹

bash snippet

โœ… Extracts specific fields from a comma-separated file.

๐Ÿ”น Change output delimiterโ€‹

bash snippet


๐Ÿ” Loopsโ€‹

๐Ÿ”น Print all fields in one columnโ€‹

bash snippet


๐Ÿงช BEGIN & END Blocksโ€‹

bash snippet

๐Ÿ“ค Output:


๐Ÿงฐ Practical Use Casesโ€‹

๐Ÿ“ Disk usage summaryโ€‹

bash snippet

โœ… Lists partition name and usage %.

๐Ÿ” Search logs for 404โ€‹

bash snippet

โœ… Filters out 404 HTTP status codes.

๐Ÿงน Remove empty linesโ€‹

bash snippet


โš ๏ธ Common Errorsโ€‹

ErrorReasonFix Example
awk: syntax errorMissing quotes or braces'...'
awk: can't open fileFile does not exist or permission errorcheck path
Fields not splittingWrong delimiteruse -F

โœ… Summaryโ€‹

AWK is a must-know for anyone working with structured text. Use it for filtering, field extraction, simple math, and formatted reporting.


๐Ÿ“š Want more?

  • man awk
  • GNU gawk for extended capabilities
  • awk.dev