Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

awk Command Guide for Analyzing Text

This guide helps you understand and use the awk command, a small programming language built into Linux for selecting and transforming columnar text.


What is awk, and Why Use It?

The awk command processes text line by line, splitting each line into fields (columns) that you can select, compute on, and reformat. Named after its authors — Aho, Weinberger, and Kernighan — it is a full language: variables, conditions, loops, and functions.

Why Learn awk?

  • Column math: Sum, average, and compare numbers embedded in text — logs, reports, config exports.
  • Selective printing: “Show me only lines where column 3 is greater than 100” is one line of awk.
  • Reporting without tools: Turn a raw file into a formatted report without writing a script.
  • It’s everywhere: Every Linux system has awk; nothing needs installing.

grep answers “where is it?”, sed answers “change it”. awk answers “what are the numbers?”


1. Print Specific Columns

awk splits each line into fields $1, $2, $3, … separated by whitespace by default:

awk '{ print $1 }' data.txt
  • Prints the first column of every line.

Print several columns:

awk '{ print $1, $3 }' data.txt

Fields are re-joined with a single space. To use a different separator:

awk -F: '{ print $1 }' /etc/passwd
  • -F: splits on colons instead — the standard trick for /etc/passwd.

Example — list usernames and home directories:

awk -F: '{ print $1, $6 }' /etc/passwd

2. Filter Lines with Conditions

Add a condition between slashes and the action block:

awk '$3 > 100 { print }' data.txt
  • Prints only lines whose third field is greater than 100.

Comparison and pattern operators:

OperatorMeaning
==, !=Equal / not equal
<, >, <=, >=Numeric comparison
~Matches a regex
!~Does not match
/pat/Shorthand for $0 ~ /pat/

Example — lines containing “error” anywhere:

awk '/error/ { print }' app.log

3. The BEGIN and END Blocks

awk programs have three phases: code in BEGIN runs before any input, the main block runs once per line, and END runs after the last line:

awk 'BEGIN { print "Report start" } { print } END { print "Report end" }' data.txt

This is how you print headers and footers around output:

awk 'NR==1 { print "Name   Size" } { print $1, $5 } END { print "Total:", NR, "lines" }' file.txt

4. Built-in Variables

awk keeps track of the data for you:

VariableMeaning
$0The whole line.
$1..$nFields of the line.
NFNumber of fields in the current line.
NRCurrent line number (across all files).
FNRLine number within the current file.
FS / OFSInput / output field separator.

Example — print the last field of every line, whatever the line length:

awk '{ print $NF }' data.txt

5. Sum and Average a Column

The classic awk task — column arithmetic:

awk '{ sum += $3 } END { print sum }' data.txt

Sum the third column and print it in END. Add the count for an average:

awk '{ sum += $3; n++ } END { print "avg:", sum / n }' data.txt

Sum only matching lines:

awk '/ERROR/ { sum += $2 } END { print "total errors:", sum }' app.log

6. Reshape and Reformat Output

Because awk prints whatever you tell it, it’s a formatting tool:

awk -F: '{ printf "%-20s %s\n", $1, $7 }' /etc/passwd
  • Left-aligns usernames in a 20-character column, then the shell path.

Change the field separator on output:

awk 'BEGIN { OFS="," } { print $1, $2, $3 }' data.txt

7. Multiple Files and Patterns Combined

awk handles several files at once, using FNR to track per-file line numbers:

awk 'FNR==1 { print "== " FILENAME " ==" } { print }' file1.txt file2.txt

Combine conditions with && and \|\|:

awk '$3 > 100 && $1 == "server01" { print }' data.txt

8. awk, sed, or grep?

NeedTool
Find lines containing a patterngrep
Replace text in placesed
Select, compute, or reformat columnsawk
Sum numbers in a columnawk
Extract a literal column when input is regularcut

Common Pitfalls

  • Forgetting -F for non-whitespace input. /etc/passwd is colon-separated; without -F:, $1 is the whole line.
  • Comparing strings with > instead of ==. > forces numeric comparison; "abc" > "abd" is a character-code comparison, rarely what you want.
  • Quoting the program. Always single-quote the awk program so the shell doesn’t expand $1.
  • Assuming awk edits files. Like sed without -i, it prints to stdout; redirect (>) or use -i-style workarounds to save results.
  • GNU vs POSIX differences. Some extensions (like genvec arrays) are not portable; stick to the core language for scripts that must run anywhere.

PageRelationship
grepPattern matching without the column machinery.
sedStream editing for replacements; awk for analysis.
cutSimpler column extraction when no math is needed.
sortPair with awk to rank computed columns.

awk Cheatsheet

CommandWhat It Does
awk '{print $1}' fPrint the first column.
awk -F: '{print $1}' fSplit on colons instead of spaces.
awk '$3 > 100' fPrint lines whose 3rd field exceeds 100.
awk '/pat/' fPrint lines matching pat.
awk '{print $NF}' fPrint the last field.
awk '{s+=$1} END{print s}' fSum the first column.
awk 'NR==1' fPrint only the first line.
awk '{print $1, $3}' fPrint columns 1 and 3.
awk 'BEGIN{OFS=","}{print $1,$2}' fComma-separated output.
awk -F: '{print $1,$6}' /etc/passwdUsernames and home dirs.
awk 'FNR==1{print FILENAME}' f1 f2Show each filename once.