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.
grepanswers “where is it?”,sedanswers “change it”.awkanswers “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:
| Operator | Meaning |
|---|---|
==, != | 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:
| Variable | Meaning |
|---|---|
$0 | The whole line. |
$1..$n | Fields of the line. |
NF | Number of fields in the current line. |
NR | Current line number (across all files). |
FNR | Line number within the current file. |
FS / OFS | Input / 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?
| Need | Tool |
|---|---|
| Find lines containing a pattern | grep |
| Replace text in place | sed |
| Select, compute, or reformat columns | awk |
| Sum numbers in a column | awk |
| Extract a literal column when input is regular | cut |
Common Pitfalls
- Forgetting
-Ffor non-whitespace input./etc/passwdis colon-separated; without-F:,$1is 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
awkprogram so the shell doesn’t expand$1. - Assuming
awkedits files. Likesedwithout-i, it prints to stdout; redirect (>) or use-i-style workarounds to save results. - GNU vs POSIX differences. Some extensions (like
genvecarrays) are not portable; stick to the core language for scripts that must run anywhere.
Related Pages
| Page | Relationship |
|---|---|
grep | Pattern matching without the column machinery. |
sed | Stream editing for replacements; awk for analysis. |
cut | Simpler column extraction when no math is needed. |
sort | Pair with awk to rank computed columns. |
awk Cheatsheet
| Command | What It Does |
|---|---|
awk '{print $1}' f | Print the first column. |
awk -F: '{print $1}' f | Split on colons instead of spaces. |
awk '$3 > 100' f | Print lines whose 3rd field exceeds 100. |
awk '/pat/' f | Print lines matching pat. |
awk '{print $NF}' f | Print the last field. |
awk '{s+=$1} END{print s}' f | Sum the first column. |
awk 'NR==1' f | Print only the first line. |
awk '{print $1, $3}' f | Print columns 1 and 3. |
awk 'BEGIN{OFS=","}{print $1,$2}' f | Comma-separated output. |
awk -F: '{print $1,$6}' /etc/passwd | Usernames and home dirs. |
awk 'FNR==1{print FILENAME}' f1 f2 | Show each filename once. |