Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Part 1 · Basics · Lesson 05 · 30 minutes

Pick fields and calculate with awk

After this lesson you can
  • Print chosen fields of each line
  • Select lines with a test on a field
  • Add up a column and read a file with another separator
Lab files of this lesson (5)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

Your team lead has a short report of file transfers: the time, the host, the user, the number of bytes and a status. "How many bytes did we send, and how many transfers were refused?" she asks. grep can find the refused lines and cut can keep a column, but neither can add numbers. The tool for this job is awk. A real report has thousands of lines, so you learn the method on a small file.

Recall

Why does "sort | uniq -c" give the right count, and "uniq -c" alone does not?

uniq merges only equal lines that are next to each other. sort first puts equal lines together.

What does "grep -v sshd auth.log" print?

Every line that does not contain sshd. -v turns the match round.

The idea

awk reads a file one line at a time. It cuts each line into fields, which are the pieces between spaces. $1 is the first field, $2 the second, and $NF the last one (NF is the number of fields). $0 is the whole line.

The text between single quotes is the program. It has a condition and an action in braces: $2 == 443 {print $1} means "when field 2 is 443, print field 1". A program without a condition runs its action on every line. A program without an action prints the lines that match.

One awk command, taken apart
awkthe tool'$2 == 443 {print $1}'the program, in single quotes$2 == 443condition: field 2 is 443{print $1}action: print field 1sizes.txtthe file to readawkthe tool'$2 == 443 {print $1}'the program, in single quotes$2 == 443condition: field 2 is 443{print $1}action: print field 1sizes.txtthe file to read
What awk does with each line
Read a lineSplit into fieldsTest the conditionRun the actionat spaces, or at the -F textfor example $2 == 443print, or add to a totalthe next lineRead a lineSplit into fieldsTest the conditionRun the action1234
  1. Read a line → Split into fields: at spaces, or at the -F text
  2. Split into fields → Test the condition: for example $2 == 443
  3. Test the condition → Run the action: print, or add to a total
  4. Run the action → Read a line: the next line

Two names help. NR is the number of the line that awk reads now. The action after END runs once, after the last line: that is the place for a total.

Worked example

1. Print fields

Make a small table of servers. printf prints text from a template, and \n ends a line. Then print the first field of each line, two fields, and the last field.

cd ~/krlab/linux-basics
printf 'host port bytes\nweb1 443 5120\nweb2 80 2048\ndb1 5432 900\nweb3 443 3300\n' > sizes.txt
awk '{print $1}' sizes.txt
awk '{print $1, $3}' sizes.txt
awk '{print $NF}' sizes.txt
host
web1
web2
db1
web3
host bytes
web1 5120
web2 2048
db1 900
web3 3300
bytes
5120
2048
900
3300

A comma in print $1, $3 puts a space between the two fields.

2. Select lines with a condition

== tests for "equal to", and > for "greater than". Print the host when the port is 443, and then the hosts that sent more than 3000 bytes.

awk '$2 == 443 {print $1}' sizes.txt
awk '$3 > 3000 {print $1, $3}' sizes.txt
web1
web3
host bytes
web1 5120
web3 3300

The header line host port bytes is in the second result. The word bytes is not a number, so awk compares it as text, and in text order bytes comes after 3000. A table with a header needs a guard.

3. Skip the header with NR

The header is line 1, so NR > 1 selects the data lines. && means "and": both tests must be true.

awk 'NR > 1 && $3 > 3000 {print $1, $3}' sizes.txt
web1 5120
web3 3300

4. Add up a column

The action s += $3 adds field 3 to the variable s. A variable starts empty, which counts as 0. The END action prints the total after the last line. The data lines are NR - 1, so the mean is the total divided by that number.

awk 'NR > 1 {s += $3} END {print s}' sizes.txt
awk 'NR > 1 {s += $3} END {print s, s / (NR - 1)}' sizes.txt
awk '$2 == 443 {n++} END {print n}' sizes.txt
awk '$2 == 22 {n++} END {print n + 0}' sizes.txt
11368
11368 2842
2
0

n++ adds 1 to n, so the third command counts the lines on port 443. When no line matches, n stays empty and print n shows an empty line. The fourth command writes n + 0, which forces a number: 0.

5. Change the separator with -F

Many files do not use spaces. In /etc/passwd the fields are split by colons, and the third one is the user ID. -F: (field separator) sets the colon. Print the accounts whose user ID is 0. Only root should be there.

awk -F: '$3 == 0 {print $1}' /etc/passwd
root

A line of /etc/passwd has seven fields, split by colons. Field 5 is empty in the lines below.

One line of accounts.txt
alice$1: the user namex$2: the password is elsewhere1001$3: the user ID1001$4: the group ID/home/alice$6: the home folder/bin/bash$7: the login shellalice$1: the user namex$2: the password is elsewhere1001$3: the user ID1001$4: the group ID/home/alice$6: the home folder/bin/bash$7: the login shell

Make a file of accounts of your own, and print the user and the shell of the first two.

printf 'alice:x:1001:1001::/home/alice:/bin/bash\nbob:x:1002:1002::/home/bob:/bin/bash\ncarol:x:1003:1003::/home/carol:/usr/sbin/nologin\n' > accounts.txt
awk -F: '{print $1, $7}' accounts.txt | head -n 2
alice /bin/bash
bob /bin/bash

6. Use awk inside a pipe

awk reads a pipe as it reads a file. Use the login log of lesson 4 (auth.log, in the lab folder). In the failed lines the address is always the fourth field from the end, written $(NF-3). The result is the same ranking as before, with one tool in place of grep -o and cut.

grep "Failed password" auth.log | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn
      5 203.0.113.50
      1 198.51.100.7

Your turn

Run this block once. It builds the report and a list of accounts. It is not the task.

mkdir -p ~/krlab/linux-basics/awk && cd ~/krlab/linux-basics/awk
cat > transfers.txt <<'EOF'
time host user bytes status
09:00 web1 alice 5120 ok
09:02 web1 bob 2048 ok
09:03 db1 carol 900 denied
09:05 web2 alice 15360 ok
09:07 db1 dave 4096 denied
09:08 web1 bob 300 ok
09:11 web2 carol 12288 ok
09:15 db1 dave 700 denied
EOF
cat > accounts.txt <<'EOF'
alice:x:1001:1001::/home/alice:/bin/bash
bob:x:1002:1002::/home/bob:/bin/bash
carol:x:1003:1003::/home/carol:/usr/sbin/nologin
dave:x:1004:1004::/home/dave:/bin/bash
svc-web:x:1005:1005::/srv/web:/usr/sbin/nologin
EOF

Answer your lead from the two files. There are no steps here: use awk. Do not count the header line of transfers.txt.

Last, print the user and the host of every transfer that sent more than 10000 bytes, one pair on each line.

Check yourself

Why does awk '$3 > 3000' print the header line of a table?

The header holds a word in field 3, not a number. awk then compares as text, and the word sorts after 3000. Add NR > 1, or test that the field is a number.

What is the difference between $NF and $(NF-1)?

$NF is the last field. $(NF-1) is the field before the last one. The brackets are needed because $NF-1 would take the last field and subtract 1.

Your total prints an empty line, and you expected 0. Why?

No line matched, so END ran with a variable that was never set. Print s + 0, which turns the empty value into the number 0.

When do you use cut, and when awk?

cut is enough to keep columns of a file with one fixed separator. awk is the tool when you must test a value, calculate, or cope with a different number of spaces between the fields.

Field notes

  • awk has arrays. {c[$2]++} END {for (k in c) print k, c[k]} counts the lines for each host with no sort | uniq -c. The order of the loop is not fixed, so pipe the result to sort.
  • Several awks exist. Debian and Ubuntu use mawk by default, many other systems use GNU gawk. The lines of this lesson work in both. GNU-only features, such as gensub, fail in mawk.
  • Use -v name=value to pass a value into the program without editing the quotes: awk -v limit=3000 '$3 > limit'. Do not build a program by pasting text from a log into it.
  • Check totals with a second method, for example grep -c against awk '{n++} END {print n}', before you put a number in a report.