๐ง 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โ
Variable | Description |
---|---|
$0 | Entire line |
$1,$2 | Fields |
NF | Number of fields in current line |
NR | Current line number |
FS | Input field separator |
OFS | Output 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โ
๐น Add header and footerโ
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โ
Error | Reason | Fix Example |
---|---|---|
awk: syntax error | Missing quotes or braces | '...' |
awk: can't open file | File does not exist or permission error | check path |
Fields not splitting | Wrong delimiter | use -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