Linux Command Line · Lesson 19 of 43
Working with columns using awk
Use awk to split lines into fields, filter rows by condition, calculate sums and averages and format reports from columnar text.
UNDERSTAND IT. THEN TRY IT.
What you can do after this lesson
You will pick out columns, filter rows by a condition and calculate sums and averages from text, right in the terminal. awk is a small programming language built for tables of data, and the few patterns in this lesson cover most daily uses.
Fields and the print action
By default awk splits each line into fields at runs of spaces or tabs. $1 is the first field, $2 the second, $NF the last, and $0 the entire line:
cd ~/project
awk '{print $1, $2}' logs/app.log | head -n 3
awk '{print $NF}' logs/app.log | head -n 32026-01-15 10:00:01
2026-01-15 10:00:05
2026-01-15 10:01:12
started
in
81%The program is written in single quotes and has the form pattern { action }. With only an action, it runs on every line. print with commas separates items with a space.
Other separators
For CSV and similar data, set the separator with -F:
awk -F, '{print $1 " scored " $3}' data/scores.csv | head -n 3name scored score
Asha scored 82
Ben scored 67Text in double quotes is a literal string, and placing items next to each other joins them. The first line shows the header, because awk treats every line alike.
Patterns: choosing lines
A pattern before the braces limits the action to lines where it is true. It can be a regular expression between slashes, or a condition:
awk '/ERROR/ {print $2, $4, $5}' logs/app.log
awk -F, '$3 > 80 {print $1}' data/scores.csv
awk -F, 'NR > 1 && $2 == "red" {print $1}' data/scores.csv10:02:40 database timeout
10:02:44 database timeout
name
Asha
Chitra
Ela
Ben
ElaIn the second example, $3 > 80 also let the header through: the header field score is text, and awk compares text with a number as text, where score sorts after 80. That is why the third example uses NR > 1 to skip the header. The && in the third example means "and". Other operators are || (or), ! (not), ==, !=, <, >=. A pattern with no action prints matching lines, so awk '/ERROR/' logs/app.log behaves like grep.
Built-in variables
NRis the number of the current line, counted across all input.NFis the number of fields on the line.FSis the input field separator, which-Fsets.FILENAMEis the name of the current file.
awk '{print NR ": " NF " fields"}' docs/notes.txt1: 7 fields
2: 5 fields
3: 8 fields
4: 4 fields
5: 4 fieldsCalculations: sums and averages
Variables need no declaration, and start at zero. The END block runs once after the last line, so it is where totals are printed. This adds the scores, skipping the header:
awk -F, 'NR > 1 {sum += $3} END {print "total:", sum}' data/scores.csv
awk -F, 'NR > 1 {sum += $3; n++} END {print "average:", sum / n}' data/scores.csv
awk -F, 'NR > 1 {sum += $3; n++} END {printf "average: %.1f\n", sum / n}' data/scores.csvtotal: 469
average: 78.1667
average: 78.2printf formats numbers as in C: %.1f means one decimal place, %s a string and \n ends the line. Note that print does not need it, because it adds a newline itself.
Counting by group with arrays
awk has associative arrays, which makes group counting short. This counts how many log lines each level has:
awk '{count[$3]++} END {for (level in count) print level, count[level]}' logs/app.log | sortERROR 2
INFO 5
WARN 1The array count is indexed by the third field. The sort at the end is there because awk does not promise any particular order when looping over an array.
BEGIN: before the first line
BEGIN runs once before any input, which is the place to set variables or print a heading:
awk -F, 'BEGIN {print "Team report"} NR > 1 {print "- " $1 " (" $2 ")"}' data/scores.csv | head -n 3Team report
- Asha (blue)
- Ben (red)awk, cut, sed or grep?
Use grep to find lines, cut for fixed columns, sed to substitute text, and awk when you need conditions, calculations or irregular spacing between columns. awk copes with several spaces between fields, which cut cannot.
Common mistakes
Using double quotes around the whole program. The shell expands $1 inside double quotes before awk sees it. Use single quotes.
Forgetting the header line. Skip it with NR > 1.
Comparing numbers as text. Fields that look like numbers compare numerically only when both sides are numbers; check unexpected results.
Forgetting the separator. For CSV use -F,. For fields with quoted commas, a plain awk is not enough; use a CSV-aware tool.
Exercise
Print the user names from the login lines of logs/app.log (the fifth field). Show the names of people in data/scores.csv with a score of 75 or more. Then calculate the highest score with an END block, using if ($3 > max) max = $3 for each line after the header.
KNOWLEDGE CHECK
A quick check. You’ve got this.
Try each question. Every answer comes with an explanation.
Ready for the next small win?
Mark the lesson complete when you are ready.