Skip to content
Français
Sync not enabled: your progress stays in this browser My learning
Select theme
Français

awk: filter, compute and group columns

By updated

Improve this page

A sales export to add up, the 4xx and 5xx errors of a web log to count per IP address: as soon as the job is about the columns of a text, awk does it in one command, without a Python script. It reads a file line by line, splits each line into fields, applies an action to the lines that meet a condition, and can keep totals from one line to the next.

grep picks whole lines, cut extracts columns without any computation, sed transforms text. This page adds what none of the three does: reason about the value of a field, compute, group, and know when awk is no longer the right tool.

What you will learn

  • Predict what awk prints depending on -F and NR > 1
  • Read the fields of a line with $1, $NF, NR and NF
  • Filter by field: number, text or regular expression
  • Compute a sum, a count and an average in END
  • Group by value with an associative array
  • Align the output with printf and pass a shell variable with -v
  • Choose between awk, cut, sort, uniq, jq and a real programming language

Prerequisites

You know how to use redirections and pipes, you have read the overview of awk in Filter and transform text ($1, -F, a condition, a total in END), Sort, count and deduplicate (sort -k2) and Regular expression basics for the ~ pattern. The awk program is written between single quotes, so that the shell does not interpret $1.

Create the practice folder

Type these commands as they are: they create three files in ~/awk-lab. The commands of the lesson are run from this folder. access.log is an excerpt of an Apache and nginx log in the Common Log Format (the Combined format, nginx's default, adds the Referer and the User-Agent at the end: the status code stays in $9 as long as the request has three words), commandes.csv is a sales export with a header line, and ventes.csv is the small file of the map further down.

Terminal window
mkdir -p ~/awk-lab && cd ~/awk-lab
export LC_ALL=C.UTF-8
cat > access.log <<'EOF'
192.168.1.10 - alice [09/Apr/2026:08:12:03 +0200] "GET /index.html HTTP/1.1" 200 1043
10.0.0.5 - bob [09/Apr/2026:08:12:44 +0200] "POST /login HTTP/1.1" 401 219
192.168.1.10 - alice [09/Apr/2026:08:13:01 +0200] "GET /dashboard HTTP/1.1" 200 5120
10.0.0.99 - - [09/Apr/2026:08:13:37 +0200] "GET /admin HTTP/1.1" 403 162
10.0.0.5 - bob [09/Apr/2026:08:14:02 +0200] "POST /login HTTP/1.1" 200 874
172.16.0.3 - charlie [09/Apr/2026:08:14:50 +0200] "GET /api/users/42 HTTP/1.1" 404 145
192.168.1.10 - alice [09/Apr/2026:08:15:12 +0200] "DELETE /api/orders/7 HTTP/1.1" 500 302
EOF
cat > commandes.csv <<'EOF'
produit,region,quantite,prix_unitaire
laptop,nord,5,1200
serveur,sud,2,3500
switch,nord,10,450
laptop,est,3,1200
serveur,nord,1,3500
switch,sud,8,450
disque,est,20,80
EOF
printf '%s\n' nom,montant Alice,120 Bob,80 Chloe,200 > ventes.csv

The outputs of the lesson come from gawk 5.2.1 and mawk 1.3.4. Two implementations of awk coexist: mawk by default on Debian and Ubuntu, gawk on AlmaLinux. They give the same outputs, except where the text says otherwise. export LC_ALL=C.UTF-8 makes their error messages appear in English, as shown here. The file contents use French words, which the commands keep: commandes is "orders", ventes "sales", produit "product", quantite "quantity", prix_unitaire "unit price", nord, sud and est are north, south and east, serveur is "server", disque "disk", nom "name" and montant "amount".

The awk command in detail

An awk command is written in this order: the options, then the program between single quotes, then the file or files. The program is made of a pattern, which chooses the lines, and an action between braces, which says what to do with them. Without a pattern, every line is processed; without an action, the whole line is printed. Without a file, awk reads standard input, so the output of a pipe.

Anatomy of the command

Syntaxawk [options] 'pattern { action }' [file...]

  1. awk the program runThe shell command. On Debian and Ubuntu, awk is mawk by default; on AlmaLinux, gawk.
  2. -F, an optionoptional-F chooses the field separator, -v passes a value to the program.
  3. NR == 2 the patternoptionalSelects the lines: a comparison, a regular expression /text/, a range. With no pattern, every line.
  4. { print $1 } the actionoptionalWhat to do with the line. With no action, awk prints the whole line.
  5. ventes.csv the fileoptionalOne or more files. Without a file, awk reads standard input.

OutputAlice

How awk reads a file, line by line

awk repeats the same cycle for each line: it reads it, splits it into fields, evaluates the pattern, and runs the action if the pattern is true. The END block runs only once, after the last line. The map follows this cycle on ventes.csv: it keeps the amounts of at least 100, prints the names and adds them up. It uses $1 and $2 (first and second field), NR (number of the line being read), -F, (the comma separates the fields) and END; the next sections detail each of them.

Before clicking, predict what comes out in four cases: without -F, or NR > 1, with -F, alone, with NR > 1 alone, with both. For each one, note the names printed and the value of total. Then check with the map: it shows on every line whether the pattern is true, and why.

Mental model

How awk reads a file

read a linesplit it into fieldsif the pattern is true, run the action and start again; END only once, at the end

$ awk -F, 'NR > 1 && $2 >= 100 { total += $2; print $1 } END { print "total", total }' ventes.csv

  1. awk reads line 1 and splits it at the commas: $1 is the name, $2 the amount.
  2. NR is 1: NR > 1 is false. The header is skipped, the rest of the pattern is not evaluated.
  3. awk reads line 2 and splits it at the commas: $1 is the name, $2 the amount.
  4. 120 is at least 100: the pattern is true, awk runs the action.
  5. The action adds the amount (total: 120) and prints Alice.
  6. awk reads line 3 and splits it at the commas: $1 is the name, $2 the amount.
  7. 80 is below 100: the pattern is false, awk moves to the next line.
  8. awk reads line 4 and splits it at the commas: $1 is the name, $2 the amount.
  9. 200 is at least 100: the pattern is true, awk runs the action.
  10. The action adds the amount (total: 320) and prints Chloe.
  11. No more lines: the END block runs once and prints the total, 320.

What the animation shows

  1. One line, several fields. awk splits each line: $1, $2… and $0 for the whole line. -F chooses the separator.
  2. A pattern, an action. The action between braces runs only if the pattern is true. With no pattern, it applies to every line.
  3. Variables survive from line to line: total keeps its value until END.
  4. A wrong separator raises no error: the fields are empty, the result is wrong, the exit code stays 0.

Golden rules

Check the splitting first

Print the number of fields and one field before computing:

awk -F, '{ print NF, $2 }' ventes.csv

Skip the header

Compared with a number, a text turns into a text comparison. Leave the first line out:

awk -F, 'NR > 1 { print $2 }' ventes.csv

Essential vocabulary

In the program · variables and blocks

$1
The first field of the lineawk -F, '{ print $1 }' ventes.csv → 4 names, header included
NR
The number of the line readawk 'NR == 2' ventes.csv → Alice,120
NF
The number of fieldsawk -F, '{ print NF }' ventes.csv → 2 fields per line
END
Block run after the last lineawk 'END { print NR }' ventes.csv → 4

Options and output · on the command line, or in the action

-F,
The field separatorawk -F, 'NR == 3 { print $2 }' ventes.csv → 80
-v
Pass a value to the programawk -F, -v min=150 'NR > 1 && $2 > min' ventes.csv → Chloe,200
BEGIN
Block run before the first lineawk 'BEGIN { print 6 * 7 }' → 42
printf
Print with a formatawk -F, 'NR == 2 { printf "%s=%d\n", $1, $2 }' ventes.csv → Alice=120

Split a line into fields: $1, $NF, NR and NF

awk numbers the fields of a line from 1, splitting on spaces by default. $0 is the whole line, $NF the last field, and NF the number of fields of the line.

In this format, the client address is the first field and the HTTP code the ninth. You designate a piece of data by its position, not by its shape; a malformed request, with fewer than three words, would shift everything. The program between braces runs once per line, and print separates its arguments with a space.

Terminal window
awk '{print NR, NF, $9, $NF}' access.log
Output
1 10 200 1043
2 10 401 219
3 10 200 5120
4 10 403 162
5 10 200 874
6 10 404 145
7 10 500 302

Each line starts with its number (NR), followed by the number of fields (NF, always 10 here), the HTTP code ($9) and the last field ($NF), which is the size of the response here. If a field number does not exist, awk prints no error: the field is empty. To locate a piece of data in an unknown line, print the number of fields with the line: awk '{print NF, $0}' file. With print $1, $2, the comma inserts the output separator OFS (a space); print $1 $2 glues the two fields together with nothing between them.

Choose the separator with -F

The -F option changes the field separator. /etc/passwd lists the local accounts, one per line, with seven fields separated by colons. cut -d: -f1,7 would do the same extraction, but awk can also filter on the value of a field, for example keep the accounts whose shell is /bin/bash. Your accounts differ from those of the example.

Terminal window
awk -F: '{print $1, $7}' /etc/passwd
Output (accounts of the test machine)
root /bin/bash
daemon /usr/sbin/nologin
bob /bin/bash
alice /bin/zsh
sshd /usr/sbin/nologin

$1 is the account name and $7 its login shell. Put -F: before the program: after it, awk takes it for a file name and stops on fatal: cannot open file `-F:' for reading (gawk) or cannot open "-F:" (mawk).

On a CSV, the separator is the comma. -F';' splits on a semicolon and -F'\t' on a tab. You skip the header line with NR > 1 and multiply two fields directly.

Terminal window
awk -F, 'NR > 1 {print $1, $3*$4}' commandes.csv
Output
laptop 6000
serveur 7000
switch 4500
laptop 3600
serveur 3500
switch 3600
disque 1600

Seven order lines give seven amounts, and the header is gone. NR == 1 { next } is an equivalent form: next abandons line 1 and moves to the next one. It becomes useful when the program has several blocks, because the header is discarded once, at the top of the program. With several files as arguments, NR keeps counting from one file to the next; FNR restarts at 1 for each file.

Filter lines with a pattern

A program is written pattern { action }. The pattern can be a comparison on a field, a regular expression between slashes, or a combination with && (and), || (or) and ! (not). It goes before the braces: inside them, it would no longer select anything.

To compare, write ==: $1 = "admin" replaces the first field in the output and keeps every line. awk does not modify its file, but awk ... file > file empties it before it is read.

Compare numbers

awk compares as numbers the fields that look like a number. This is the difference with grep, which only knows text: grep 4 would find 404 as well as 1043, whereas $9 >= 400 compares values.

Terminal window
awk '$9 >= 400 {print $1, $9, $7}' access.log
Output
10.0.0.5 401 /login
10.0.0.99 403 /admin
172.16.0.3 404 /api/users/42
192.168.1.10 500 /api/orders/7

Only the four requests in error come out. The trap appears when a field does not look like a number: awk then compares text, and "abc" is greater than "400" in character order.

Terminal window
echo abc | awk '$1 >= 400'
echo abc | awk '$1+0 >= 400'
Output of the first command (nothing for the second)
abc

The first command prints abc on mawk as on gawk, with no message: these are stray lines in your result. Adding +0 forces the numeric comparison, abc then equals 0 and the second command prints nothing. On a file whose cleanliness you do not control, write $1+0.

The same trap is triggered as soon as an operand is a constant between double quotes: $2 > "100" compares text, and "9" comes after "100". Write $2 > 100.

Compare text

== requires equality on the whole field. In this log, the request is between double quotes, so the sixth field is literally "POST, with the opening quote attached. The sequence "\"POST" builds this string, the backslash protecting the inner quote.

Terminal window
awk '$6 == "\"POST" {print $1, $7, $9}' access.log
Output
10.0.0.5 /login 401
10.0.0.5 /login 200

Search with a regular expression

~ and !~ apply a regular expression to one specific field: grep 192.168 would also return a line where this address appears in the URL. The pattern is not anchored by default, hence the ^ to require the start of a field, and the dots are escaped as \.: a bare dot accepts any character.

Terminal window
awk '$1 ~ /^192\.168\./ {print $1, $9}' access.log
awk '$3 !~ /alice/ {print $1, $3, $9}' access.log
Outputs of the two commands
192.168.1.10 200
192.168.1.10 200
192.168.1.10 500
10.0.0.5 bob 401
10.0.0.99 - 403
10.0.0.5 bob 200
172.16.0.3 charlie 404

The first command keeps the three requests of the 192.168 network, the second drops alice's. Without a field in front, /ERROR|WARN/ tests the whole line. A regular expression between double quotes ("/ERROR/") becomes a plain string, always true: everything comes out.

Compute a sum, a count and an average with END

For a total, a count or an average, you accumulate line by line in variables, then print in END. A variable that was never filled equals 0 in a calculation and prints as empty: there is nothing to declare. A variable that you increment on every line works as a counter.

BEGIN { ... } runs before the first line: you set the separator there with FS, which is what -F does, or print a report title. The program here spans several lines, inside a single pair of single quotes; '\'' inserts an apostrophe in the printed text.

Terminal window
awk -F, 'NR == 1 { next }
{
total += $3 * $4
lignes++
}
END {
print "Lignes traitées :", lignes
print "Chiffre d'\''affaires total :", total, "€"
}' commandes.csv
Output
Lignes traitées : 7
Chiffre d'affaires total : 29800 €

total adds up the amount of each of the seven lines, lignes ("lines") counts them, and END runs only once. The text printed by the program is French here too: "Lignes traitées" means "lines processed" and "Chiffre d'affaires total" means "total revenue". A program that only contains { total += $3 } prints nothing: nobody asks for the result. An average is computed the same way, in END: the sum divided by a number of lines.

An average that is too low Exercise 1 of 2 · ~6 min · terminal

A colleague wants the average quantity per order in commandes.csv, which contains seven orders. They run awk -F, 'NR > 1 { somme += $3 } END { print somme / NR }' commandes.csv: they did skip the header, and yet the average looks low to them. No error appears. What does their command compute, and how do you get the real average?

Run the colleague's command

Run it and note the average it prints.

See what NR equals

Print the line number and the third field of each line, then compare the last number with the number of orders.

Fix it and run it again

Write the command that divides by the number of orders, and note the new average.

A hint 1 / 1

Look at the number the sum is divided by.

I have tried: show the solution
Terminal window
awk -F, 'NR > 1 { somme += $3 } END { print somme / NR }' commandes.csv
awk -F, '{ print NR, $3 }' commandes.csv
awk -F, 'NR > 1 { somme += $3; n++ } END { print somme / n }' commandes.csv
Outputs of the three commands
6.125
1 quantite
2 5
3 2
4 10
5 3
6 1
7 8
8 20
7

The NR > 1 filter keeps the header out of the sum (49), but NR still counts eight lines: the division gives 49 divided by 8, that is 6.125. With a n++ counter placed in the same block as the sum, n equals 7 and the average is 7. Dividing by NR - 1 would also give 7 here, but the error would come back as soon as another filter dropped some lines. The colleague's command succeeds with exit code 0: only the comparison with the number of orders reveals the error.

Align the output with printf

print adds a newline. printf takes the format of the C language: a format string with markers, then one value per marker. It adds no newline: end the format with \n, otherwise the whole output is glued on one line.

Terminal window
awk -F, 'NR > 1 {printf "%-10s %-6s %6d €\n", $1, $2, $3*$4}' commandes.csv
Output
laptop nord 6000 €
serveur sud 7000 €
switch nord 4500 €
laptop est 3600 €
serveur nord 3500 €
switch sud 3600 €
disque est 1600 €

Products and regions start at the same place on every line, and the amounts end at the same place. %-10s reserves ten characters for the product, padded with spaces on the right; %6d aligns the integer on six characters. %10s aligns a string to the right and %.2f prints a number with two decimals. A marker with no value stops the program: gawk answers fatal: not enough arguments to satisfy format string, mawk answers not enough arguments passed to printf.

Group with an associative array

An associative array stores values under a text key. codes[$9]++ creates the entry for the key the first time it meets it and increments it afterwards: the number of counters adapts to the values present, without you having to know the list of codes. for (c in codes) goes through all the keys. It is the equivalent of sort | uniq -c, with the added ability to add up a value per key, such as the bytes sent to each address (octets[$1] += $10).

Terminal window
awk '{codes[$9]++} END {for (c in codes) print c, codes[c]}' access.log | sort
Output
200 3
401 1
403 1
404 1
500 1

The code 200 appears three times, the other four once each. The order in which an array is traversed is not defined and may change from one implementation to another: the final sort fixes the order. A second array lets you follow a second counter on the same key. Here, the IP address indexes the number of requests and the number of errors:

Terminal window
awk '{ip[$1]++; if ($9 >= 400) err[$1]++}
END {
for (i in ip) printf "%-16s %6d %6d\n", i, ip[i], err[i]
}' access.log | sort -k2 -rn
Output
192.168.1.10 3 1
10.0.0.5 2 1
172.16.0.3 1 1
10.0.0.99 1 1

The second column counts the requests, the third the errors. Here every address has at least one error. For an address with no error, err[i] does not exist: reading it gives an empty string (%d prints it as 0) and creates the key along the way. To test without creating anything, write if (k in array).

Revenue per region Exercise 2 of 2 · ~10 min · terminal

In commandes.csv, management only cares about the laptop and serveur orders. Print the revenue (quantity times unit price) of these orders per region, one region per line, in aligned columns, sorted by region name.

Filter the right lines

Write the pattern that keeps only the two products. Print the region and the amount of each kept line, and count them.

Group by region

Replace the line-by-line printing with a sum per region, printed in END.

Align and sort

Print each region with printf on 6 characters, left-aligned, then the amount on 8 characters, right-aligned, and sort the output.

A hint 1 / 2

Two products: it is enough that one of the two matches.

A hint 2 / 2

The key of the array is the region, the value added is $3 * $4.

I have tried: show the solution
Terminal window
awk -F, 'NR > 1 && ($1 == "laptop" || $1 == "serveur") { ca[$2] += $3 * $4 }
END { for (r in ca) printf "%-6s %8d\n", r, ca[r] }' commandes.csv | sort
Output
est 3600
nord 9500
sud 7000

Four lines pass the pattern (two laptops, two servers). The ca array ("revenue") adds their amount under the key of the region, and END prints one line per region: the nord region, which has one laptop and one server, adds 6000 and 3500, that is 9500. NR > 1 is optional here, since produit is neither laptop nor serveur; $1 ~ /^(laptop|serveur)$/ gives the same result. A forgotten filter changes the figures: without it, the nord region shows 14000 instead of 9500. sort orders the regions.

Pass a shell variable with -v

Between double quotes, the shell replaces $1 before awk sees it: the program becomes { print } and the command prints the whole line instead of the column. To bring a shell value into the program, keep the single quotes and pass it with -v name=value. The program then reads name as an awk variable.

Terminal window
seuil=5000
awk -F, -v min="$seuil" 'NR > 1 && $3*$4 > min' commandes.csv
Output
laptop,nord,5,1200
serveur,sud,2,3500

Two orders exceed 5000 (6000 and 7000). The double quotes around $seuil ("threshold") protect a value that would contain spaces. -v also sets the internal variables: -v OFS="," changes the output separator.

What do mawk or gawk change?

To know which awk answers on your machine, follow the link of the program:

Terminal window
readlink -f "$(command -v awk)"
Output on Debian 13
/usr/bin/mawk

On AlmaLinux 10, the same command answers /usr/bin/gawk. The results of this lesson are the same with both, apart from error messages, except in two cases. A division by zero, for example an average over an empty file, stops gawk on fatal: division by zero attempted and makes mawk print -nan, with no message: protect it with END { if (n > 0) print somme / n }.

The other difference: on accented text, mawk counts bytes where gawk counts characters. echo été | awk '{ print length($1) }' prints 5 with mawk and 3 with gawk, substr cuts in the middle of a letter under mawk, and printf "%-5s" pads été with two spaces under gawk, none under mawk.

Which command should I use?

awk is the right fit as soon as you need to reason about the value of a field. For the other needs, a simpler tool is enough and is easier to read.

I want to...I use
Extract one or two columns, with no computation or conditioncut
Count identical lines, or sort themsort and uniq
Keep the lines that contain a patterngrep
Replace text or delete linessed
Read or modify JSONjq
Filter by field, compute, group, formatawk
Replace within a line, measure or cut a text, from awkgsub(/a/, "b"), length($1), substr($1, 1, 3), toupper($1) (bytes under mawk, see above)
A CSV whose fields contain the separator ("Dupont, Jean"), or logic of several dozen linesa real programming language, such as Python

awk -F, splits at every comma, including those inside a quoted field: for that case, a CSV parser is safer. Beyond a few lines, write the program in a file read with awk -f script.awk file: you get indentation and comments back.

Troubleshooting

When the result is wrong, first print what awk sees: awk '{print NF, $0}' file shows the number of fields of each line, and awk '{ for (i=1; i<=NF; i++) print i, $i }' file numbers each field.

SymptomLikely causeSolution
$2 is empty, or the result makes no sense, with no errorWrong separator: awk splits on spaces-F, or -F:, and check with print NF, $0
The command prints the whole line instead of the columnDouble quotes: the shell replaced $1Program between single quotes, shell value with -v
Average too low, counter too large by oneThe header was counted, or division by NR despite NR > 1NR > 1 and an n++ counter
unexpected newline or end of string (gawk), missing } near end of file (mawk)Brace, parenthesis or quote not closedCheck that every { has its } and that single quotes enclose the whole program
Output glued on a single line, or not enough argumentsprintf without \n, or more % than values\n at the end of the format, one value per marker
fatal: division by zero attempted (gawk), -nan (mawk)The divisor is 0: empty file or null counterEND { if (n > 0) print somme / n }

Clean up the practice folder

Delete the practice folder, that is ~/awk-lab and nothing else:

Terminal window
cd ~ && rm -r ~/awk-lab
unset LC_ALL

Key points

  • awk reads line by line, splits into fields ($1, $NF, $0) and applies pattern { action }; without a pattern, every line, without an action, the whole line.
  • Without -F, a CSV gives empty fields; without NR > 1, the header enters the calculations. Neither produces an error.
  • A field that does not look like a number is compared as text: force the numeric comparison with $1+0.
  • You accumulate in the body and print in END; an average is divided by a counter, protected against the value 0.
  • counter[$1]++ groups by value; the order of for (k in array) is not defined: sort with sort.
  • printf adds no newline, and a shell value comes in with -v, not with double quotes.

Knowledge check

Check that the essentials of this guide stuck. The questions cover only what has just been explained here.

Knowledge check

Check what you have learned with this interactive quiz

6 questions
6 min
70% to pass

How it works

  • The timer starts when you click Start
  • Multiple choice, true/false and short answer questions
  • You can move between questions
  • Detailed results are shown at the end

Starts the quiz and the timer

FAQ - Frequently Asked Questions

The questions most often asked about awk: passing a shell variable, processing several files, reading a CSV and writing a script in a file.