Processing columns with awk

Beginner · 20 min

Split lines into fields with awk, filter with conditions, sum and group with arrays, and avoid the header-row and shell-variable traps on BSD awk.

Before thisEditing streams with sedsort, uniq, cut, tr and wc

DistroTube · 20 min

Processing columns with awk

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by DistroTubeReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • awk reads input line by line and splits each into fields $1, $2 and so on, split on runs of whitespace by default. $0 is the whole line and NF the field count.
  • A program is pattern { action } pairs. A pattern selects lines, such as $8 == 404 or /error/, and an action like { print $1 } runs on them. BEGIN and END run before and after the input.
  • Variables start empty and numeric-zero, so awk '{s += $9} END {print s}' sums a column and c[$8]++ builds a frequency table with no setup.
  • Use -F, to change the field separator and -v name=value to pass shell values in. A shell variable inside single quotes is not substituted.
  • A non-numeric field such as a CSV header makes a comparison like $4 > 90 compare strings. Skip the header with NR > 1.

When lines are really rows

cut pulls columns but chokes on repeated spaces. grep selects lines but can’t add numbers. sed rewrites text but has no idea that field 9 is a number. When your data is rows and columns, even loosely, you want a tool that splits each line into fields, lets you test them, and does arithmetic. That’s awk, named after its authors Aho, Weinberger and Kernighan.

Its model is simple: for each input line, check each pattern { action } pair, and run the action if the pattern is true. A missing pattern means every line, and a missing action means print the line.

My awk is the BSD-derived one that ships with macOS (version 20200816), not GNU gawk. Examples use the web-server log fixture, where the status is field 8 and bytes field 9.

Fields

awk splits each line on whitespace, and runs of spaces count as one separator, which is the thing cut couldn’t do:

$ head -2 logs/access.log | awk '{print $1, $8}'
203.0.113.9 200
10.0.0.5 200
$ printf 'a   b\n' | awk '{print $2}'
b

$0 is the whole line, $NF the last field, and NF the number of fields. The comma in print $1, $8 puts a space between the two. Without it the values run together, and you’d write print $1 "|" $NF to choose the separator. For a CSV, set the separator with -F:

$ awk -F, '{print $1, $4}' data/people.csv | head -3
name score
ada 91
linus 88

NR is the current line number. awk -F, 'NR==1{print NF " fields"} END{print NR " rows"}' printed 4 fields and 6 rows.

Patterns: choosing lines

A pattern can be a regex between slashes or any condition:

$ awk '/ 404 /{c++} END{print c, "404s"}' logs/access.log
16 404s
$ awk '$8==404' logs/access.log | wc -l
      16

The second has a condition and no action, so matching lines print. NR>1 && $4>90 combines conditions. A range pattern NR==2,NR==3 selects from the first line through the second.

The header trap

Here is one that bites on nearly every CSV:

$ awk -F, '$4 > 90 {print $1}' data/people.csv
name
ada
grace
margaret

name is the header row. Its fourth field is the text score, and when one side of a comparison isn’t a number awk compares as strings, where score sorts after 90. And ada, whose score is 91, prints correctly, but linus (88) is rightly absent. Add NR>1 to skip the header. The same string rule explains why printf '10\n9\n' | awk '$1 > "9"' printed nothing: compared as text, 10 is smaller than 9. Force numbers with $1+0.

Arithmetic and arrays

Variables need no declaration. An unset one is 0 as a number and empty as a string (awk 'BEGIN{print x+0, "[" x "]"}' printed 0 []). That makes accumulators trivial:

$ awk '{s+=$9} END{print s, s/NR}' logs/access.log
913300 4566.5
$ awk -F, 'NR>1{s+=$4} END{printf "avg %.1f\n", s/(NR-1)}' data/people.csv
avg 90.0

END runs after the last line, so NR then holds the line count. Arrays are keyed by any string, so a frequency table is one line. This replaces sort | uniq -c, but the order of for (k in c) is not defined, so sort afterwards:

$ awk '{c[$8]++} END{for(k in c) print k, c[k]}' logs/access.log | sort
200 104
301 16
304 24
403 16
404 16
500 24
$ awk '{b[$1]+=$9} END{for(k in b) print k, b[k]}' logs/access.log | sort -k2 -nr | head -2
198.51.100.4 187740
203.0.113.9 185100

The second sums bytes per client. The counts match what sort | uniq -c gave in the previous lesson.

Output control and functions

printf formats like the shell’s: awk -F, 'NR>1{printf "%-10s %3d\n", $1, $4}' aligned names and scores. Assigning to a field rebuilds the line with the output separator, which also tidies spacing: echo 'a b' | awk '{$1=$1; print}' printed a b. Built-ins I ran: length($0), substr($0,2,3), toupper, gsub(/\./,"-"), and split($0, parts, "T"). A script can live in a file and be run with awk -f s.awk, and awk '!seen[$1]++' prints the first line for each distinct first field, which I used to list clients in order of appearance.

Passing shell values in

The program is in single quotes, so the shell never touches $4 or a variable named min. The way in is -v:

$ awk -v min=90 -F, 'NR>1 && $4>=min{print $1}' data/people.csv
ada
grace
margaret
$ min=90; awk -F, '$4>=min{print $1}' data/people.csv | wc -l
       6

In the second, min is an empty awk variable, so every line passes and I got all 6. That is the silent failure.

What this awk can’t do

This is the BSD awk, so GNU extras are missing:

$ awk 'BEGIN{print strftime("%Y")}'
awk: calling undefined function strftime

gensub and IGNORECASE also did nothing (the first errored, the second never matched). A pipeline that works on Linux’s gawk may fail here. Also, awk has no CSV parser: printf 'x,"a,b",y\n' | awk -F, '{print $2}' printed "a, splitting inside the quotes. For real CSV use a proper tool.

About the video

DistroTube’s “Learning Awk Is Essential For Linux Users” was published 16 June 2021 and runs 20 minutes 1 second. The description says he gives examples of basic awk commands and some ways he uses them, and it links the GNU Awk manual. It has no chapters. I couldn’t read a transcript, so I can’t say which examples it uses. As the title suggests, it’s an opinionated Linux user’s tour with the GNU flavour of awk. English by title and description. Learn Linux TV’s 16-minute awk video is the alternative.

What I did not run

gawk or mawk, getline, user-defined functions, multi-file FNR, and the -W and --version options (my attempt to print the version hung my script and I dropped it).

Next

That’s the toolkit for pipelines. The next group steps back to how the shell reads your line before running any of these commands, starting with quoting.

Check yourself

  1. 01How do you print the status code and the byte count (fields 8 and 9) of every line in the log?

    awk '{print $8, $9}' logs/access.log. The comma inserts the output field separator, a space by default.

  2. 02awk -F, '$4 > 90 {print $1}' data/people.csv also prints name, the header. Why?

    The header's fourth field is the text score, so awk compares it with 90 as strings, and 'score' sorts after '90'. Add NR > 1 to skip the header row.

  3. 03How do you count lines by status code without sort or uniq?

    awk '{c[$8]++} END {for (k in c) print k, c[k]}' logs/access.log. The array c counts each distinct value of field 8. The for loop prints in no guaranteed order, so pipe to sort.

  4. 04You write awk '$4 >= min' with min set in the shell. Why do you get every line?

    Inside single quotes the shell does not substitute, so min is an empty awk variable. Pass it with awk -v min="$min" '$4 >= min'.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark