awk
Pattern-scanning and text-processing language for field-based data
By CMD Script Team · 4 min read · Last updated
awk [OPTIONS] 'PROGRAM' [FILE...]Options
| Flag | Description |
|---|---|
-F SEP | Set the input field separator (default is whitespace) |
-v VAR=VALUE | Assign a value to a variable before the program runs |
-f FILE | Read the awk program from a file instead of the command line |
BEGIN { } | A block that runs once before any input is read |
END { } | A block that runs once after all input has been processed |
NF | Built-in variable holding the number of fields on the current line |
NR | Built-in variable holding the current line (record) number |
Distribution compatibility
- Ubuntu
- Debian
- Fedora
- Arch
- macOS
What it does
awk is a pattern-scanning and text-processing language: it reads input line by line,
automatically splits each line into fields ($1, $2, ... $NF), and runs a program
against each line — optionally restricted to lines matching a pattern. It's especially
suited to column-oriented data (log files, CSVs, ps/ls output) where you need to
extract, transform, or aggregate specific fields, going well beyond what grep or cut
alone can do.
Beginner examples
awk '{print $1}' file.txt— print the first field of every lineawk '{print $1, $3}' file.txt— print the first and third fieldsawk -F: '{print $1}' /etc/passwd— print usernames from/etc/passwd, using:as the separatorawk '/pattern/ {print}' file.txt— print only lines matching a pattern
awk -F, '{print $2}' contacts.csv
Advanced examples
- Sum a numeric column and print the total at the end:
awk '{sum += $3} END {print sum}' sales.txt - Print lines where a numeric field exceeds a threshold:
awk '$3 > 100 {print $1, $3}' data.txt - Count occurrences of each value in a field:
awk '{count[$1]++} END {for (k in count) print k, count[k]}' log.txt - Combine BEGIN, a pattern, and END for a full report:
awk 'BEGIN {print "Report:"} /ERROR/ {n++} END {print "Errors:", n}' app.log - Reformat columns, e.g. swap and relabel fields:
awk '{print $2 "\t" $1}' names.txt
awk -F, '$4 == "active" {print $1, $2}' users.csv
Common mistakes
- Forgetting
awksplits on whitespace by default, so it mishandles fields containing embedded spaces (like quoted CSV values) unless-Fand possibly a more careful field-splitting strategy are used. - Using
$1and expecting it to mean "the whole line" — that's$0;$1is the first field. - Writing
sum = $3inside a loop instead ofsum += $3, which resets the total on every line instead of accumulating it. - Confusing
NR(line/record number) withNF(number of fields on the current line) — they're easy to mix up.
Tips
- Use
-Fto set the field separator once instead of repeating it insideBEGIN {FS = "..."}for short one-liners. - Associative arrays (
count[$1]++) makeawksurprisingly capable for quick aggregation and counting tasks without writing a full script in another language. $NFalways refers to the last field on the line, regardless of how many fields there are — handy for variable-width data.
Best practices
- Reach for
awkwhen a task needs field-based logic (compute, compare, aggregate columns) — for pure text substitution,sedis usually simpler and clearer. - Keep one-liners short and readable; once an
awkprogram grows past a few lines, consider moving it to a-f script.awkfile for maintainability. - Quote
awkprograms carefully in shell scripts ('...'vs"...") to avoid the shell expanding$1-style variables beforeawkever sees them.
Try it yourself
A simulated shell with a sample home directory — experiment freely, nothing leaves your browser. Type help to list supported commands.
Real-world use cases
- Extracting and summing a specific column from a CSV export, such as totaling a sales or usage report.
- Parsing
ps auxordf -houtput to extract just the columns needed for a monitoring script. - Counting how many log lines match a given status or error type, with
BEGIN/ENDblocks producing a summary report.
Common interview questions
- What do $0, $1, and NF mean in awk?
$0is the entire current line;$1,$2, etc. are individual fields;NFis the number of fields on the current line, so$NFis the last field. - What's the difference between awk and sed?
sedis a stream editor focused on line-based text substitution;awkis a small programming language built around fields and records, with variables, arithmetic, and aggregation, making it better for column-oriented processing and computed output. - How would you sum a column of numbers in a file using awk?
awk '{sum += $N} END {print sum}' file, where$Nis the field number containing the numbers to total.
Frequently Asked Questions
How do I print a specific column from a file?
awk '{print $2}' file.txt prints the second whitespace-separated field of every line. Use -F to change the separator, e.g. awk -F, '{print $2}' file.csv for comma-separated data.
What do $1, $2, and NF mean in awk?
$1, $2, etc. refer to the first, second, and so on fields of the current line, split by the field separator. $0 refers to the whole line. NF holds the number of fields on the current line, so $NF refers to the last field.
What are BEGIN and END blocks for?
BEGIN runs once before any input lines are processed, commonly used to set variables like the field separator or print a header. END runs once after all lines have been processed, commonly used to print totals or summaries.
How is awk different from sed?
sed is primarily a line-based stream editor for substitutions and simple transformations. awk is a small programming language built around records and fields, with variables, arithmetic, conditionals, and built-in aggregation, making it better suited to column-oriented data processing and computing summaries.
Cheat sheet
Download a quick-reference cheat sheet for awk.