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
awkprints depending on-FandNR > 1 - Read the fields of a line with
$1,$NF,NRandNF - 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
printfand pass a shell variable with-v - Choose between
awk,cut,sort,uniq,jqand 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.
mkdir -p ~/awk-lab && cd ~/awk-labexport 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 104310.0.0.5 - bob [09/Apr/2026:08:12:44 +0200] "POST /login HTTP/1.1" 401 219192.168.1.10 - alice [09/Apr/2026:08:13:01 +0200] "GET /dashboard HTTP/1.1" 200 512010.0.0.99 - - [09/Apr/2026:08:13:37 +0200] "GET /admin HTTP/1.1" 403 16210.0.0.5 - bob [09/Apr/2026:08:14:02 +0200] "POST /login HTTP/1.1" 200 874172.16.0.3 - charlie [09/Apr/2026:08:14:50 +0200] "GET /api/users/42 HTTP/1.1" 404 145192.168.1.10 - alice [09/Apr/2026:08:15:12 +0200] "DELETE /api/orders/7 HTTP/1.1" 500 302EOF
cat > commandes.csv <<'EOF'produit,region,quantite,prix_unitairelaptop,nord,5,1200serveur,sud,2,3500switch,nord,10,450laptop,est,3,1200serveur,nord,1,3500switch,sud,8,450disque,est,20,80EOF
printf '%s\n' nom,montant Alice,120 Bob,80 Chloe,200 > ventes.csvThe 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...]
awk-F,NR == 2{ print $1 }ventes.csv -
awkthe program runThe shell command. On Debian and Ubuntu,awkismawkby default; on AlmaLinux,gawk. -
-F,an optionoptional-Fchooses the field separator,-vpasses a value to the program. -
NR == 2the patternoptionalSelects the lines: a comparison, a regular expression/text/, a range. With no pattern, every line. -
{ print $1 }the actionoptionalWhat to do with the line. With no action,awkprints the whole line. -
ventes.csvthe fileoptionalOne or more files. Without a file,awkreads 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
Try Input · ventes.csv
Pattern and action
Line split into fields
$ awk -F, 'NR > 1 && $2 >= 100 { total += $2; print $1 } END { print "total", total }' ventes.csv
- awk reads line 1 and splits it at the commas: $1 is the name, $2 the amount.
- NR is 1: NR > 1 is false. The header is skipped, the rest of the pattern is not evaluated.
- awk reads line 2 and splits it at the commas: $1 is the name, $2 the amount.
- 120 is at least 100: the pattern is true, awk runs the action.
- The action adds the amount (total: 120) and prints Alice.
- awk reads line 3 and splits it at the commas: $1 is the name, $2 the amount.
- 80 is below 100: the pattern is false, awk moves to the next line.
- awk reads line 4 and splits it at the commas: $1 is the name, $2 the amount.
- 200 is at least 100: the pattern is true, awk runs the action.
- The action adds the amount (total: 320) and prints Chloe.
- No more lines: the END block runs once and prints the total, 320.
What the animation shows
- One line, several fields.
awksplits each line:$1,$2… and$0for the whole line.-Fchooses the separator. - A pattern, an action. The action between braces runs only if the pattern is true. With no pattern, it applies to every line.
- Variables survive from line to line:
totalkeeps its value untilEND. - 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.csvSkip 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.csvEssential vocabulary
In the program · variables and blocks
$1- The first field of the line
awk -F, '{ print $1 }' ventes.csv→ 4 names, header included NR- The number of the line read
awk 'NR == 2' ventes.csv→ Alice,120 NF- The number of fields
awk -F, '{ print NF }' ventes.csv→ 2 fields per line END- Block run after the last line
awk 'END { print NR }' ventes.csv→ 4
Options and output · on the command line, or in the action
-F,- The field separator
awk -F, 'NR == 3 { print $2 }' ventes.csv→ 80 -v- Pass a value to the program
awk -F, -v min=150 'NR > 1 && $2 > min' ventes.csv→ Chloe,200 BEGIN- Block run before the first line
awk 'BEGIN { print 6 * 7 }'→ 42 printf- Print with a format
awk -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.
awk '{print NR, NF, $9, $NF}' access.log1 10 200 10432 10 401 2193 10 200 51204 10 403 1625 10 200 8746 10 404 1457 10 500 302Each 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.
awk -F: '{print $1, $7}' /etc/passwdroot /bin/bashdaemon /usr/sbin/nologinbob /bin/bashalice /bin/zshsshd /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.
awk -F, 'NR > 1 {print $1, $3*$4}' commandes.csvlaptop 6000serveur 7000switch 4500laptop 3600serveur 3500switch 3600disque 1600Seven 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.
awk '$9 >= 400 {print $1, $9, $7}' access.log10.0.0.5 401 /login10.0.0.99 403 /admin172.16.0.3 404 /api/users/42192.168.1.10 500 /api/orders/7Only 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.
echo abc | awk '$1 >= 400'echo abc | awk '$1+0 >= 400'abcThe 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.
awk '$6 == "\"POST" {print $1, $7, $9}' access.log10.0.0.5 /login 40110.0.0.5 /login 200Search 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.
awk '$1 ~ /^192\.168\./ {print $1, $9}' access.logawk '$3 !~ /alice/ {print $1, $3, $9}' access.log192.168.1.10 200192.168.1.10 200192.168.1.10 50010.0.0.5 bob 40110.0.0.99 - 40310.0.0.5 bob 200172.16.0.3 charlie 404The 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.
awk -F, 'NR == 1 { next }{ total += $3 * $4 lignes++}END { print "Lignes traitées :", lignes print "Chiffre d'\''affaires total :", total, "€"}' commandes.csvLignes traitées : 7Chiffre 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
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.
- awk
- END
- commandes.csv
A hint 1 / 1
Look at the number the sum is divided by.
I have tried: show the solution
awk -F, 'NR > 1 { somme += $3 } END { print somme / NR }' commandes.csvawk -F, '{ print NR, $3 }' commandes.csvawk -F, 'NR > 1 { somme += $3; n++ } END { print somme / n }' commandes.csv6.1251 quantite2 53 24 105 36 17 88 207The 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.
awk -F, 'NR > 1 {printf "%-10s %-6s %6d €\n", $1, $2, $3*$4}' commandes.csvlaptop 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).
awk '{codes[$9]++} END {for (c in codes) print c, codes[c]}' access.log | sort200 3401 1403 1404 1500 1The 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:
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 -rn192.168.1.10 3 110.0.0.5 2 1172.16.0.3 1 110.0.0.99 1 1The 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
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.
- awk
- printf
- associative array
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
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 | sortest 3600nord 9500sud 7000Four 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.
seuil=5000awk -F, -v min="$seuil" 'NR > 1 && $3*$4 > min' commandes.csvlaptop,nord,5,1200serveur,sud,2,3500Two 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:
readlink -f "$(command -v awk)"/usr/bin/mawkOn 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 condition | cut |
| Count identical lines, or sort them | sort and uniq |
| Keep the lines that contain a pattern | grep |
| Replace text or delete lines | sed |
| Read or modify JSON | jq |
| Filter by field, compute, group, format | awk |
Replace within a line, measure or cut a text, from awk | gsub(/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 lines | a 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.
| Symptom | Likely cause | Solution |
|---|---|---|
$2 is empty, or the result makes no sense, with no error | Wrong separator: awk splits on spaces | -F, or -F:, and check with print NF, $0 |
| The command prints the whole line instead of the column | Double quotes: the shell replaced $1 | Program between single quotes, shell value with -v |
| Average too low, counter too large by one | The header was counted, or division by NR despite NR > 1 | NR > 1 and an n++ counter |
unexpected newline or end of string (gawk), missing } near end of file (mawk) | Brace, parenthesis or quote not closed | Check that every { has its } and that single quotes enclose the whole program |
Output glued on a single line, or not enough arguments | printf 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 counter | END { if (n > 0) print somme / n } |
Clean up the practice folder
Delete the practice folder, that is ~/awk-lab and nothing else:
cd ~ && rm -r ~/awk-labunset LC_ALLKey points
awkreads line by line, splits into fields ($1,$NF,$0) and appliespattern { action }; without a pattern, every line, without an action, the whole line.- Without
-F, a CSV gives empty fields; withoutNR > 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 offor (k in array)is not defined: sort withsort.printfadds 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
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
Review
(0/0)Result saved on this device. It will be sent to your account at the next sync. Sync now
Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
Continue the course: Advanced redirections, here-doc and xargs
A new full quiz with random questions
Work again only on the questions you missed
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.
-v option: awk -v threshold="$var" '$2 > threshold' file.txt. Between double quotes, the shell would replace $1 and $2 before awk sees them, and the command would print the whole line.awk '{ print FILENAME, $0 }' file1 file2 prefixes each line with the name of its file. NR keeps counting from one file to the next, FNR restarts at 1 at the start of each file.-F: awk -F, '{ print $1, $2 }' file.csv. That is enough as long as no field contains the separator. A quoted field that contains a comma, such as "Dupont, Jean", is cut in two: use a CSV parser for that case. Skip the header with NR > 1.script.awk, and run it with awk -f script.awk file.txt. You keep indentation and comments, which makes a program of several lines readable and reusable.