Course outline
Course / The terminal and the language

Find the top N and answer a counting question

Lab

How to fetch and submit this lab

Once: install the tool and connect your account.

curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon login

Each lab: download it, edit the file named in the instructions, then submit.

gonomicon fetch week-1/03-06-top-n-from-a-log
cd 03-06-top-n-from-a-log
gonomicon submit

Go installed? gonomicon test runs the visible test on your computer first. Submitting also runs hidden checks on our server.

Goal

The file testdata/access.log has one request per line: ip method path status. Print how many requests had status 500, then the three most frequent IP addresses as count ip, most frequent first.

Example

If testdata/access.log held:

1.1.1.1 GET /a 200
2.2.2.2 GET /b 500
1.1.1.1 GET /c 500
1.1.1.1 POST /d 200
3.3.3.3 GET /e 404
2.2.2.2 GET /f 200

your script prints:

2
3 1.1.1.1
2 2.2.2.2
1 3.3.3.3

The first line is the number of status-500 requests. The next lines are the top three IPs: the count, one space, then the IP.

Rules

  • Edit answer.sh. Read testdata/access.log and print the result.
  • Fields are separated by single spaces: field 1 is the IP, field 2 the method, field 3 the path, field 4 the status.
  • Print the 500 count first, on its own line, as a plain number. If there are no 500s, print 0.
  • Then print at most three lines of count ip, biggest count first. If the log has only three distinct IPs, you print all three.
  • Count status only. Paths can contain digits (even 500), so look at field 4, not the whole line.
  • No two IPs in the top four have the same count, so there are no ties to worry about.
  • Spaces at the start of a line are ignored when your output is checked, so do not worry about how uniq -c pads its numbers.
  • Do not edit testdata/access.log itself. Your script only prints.

What you'll practice

cut, grep -c, sort, uniq -c, sort -nr, head -n, and combining them in pipelines.

Run it

gonomicon fetch week-1/03-06-top-n-from-a-log
cd 03-06-top-n-from-a-log
gonomicon test
gonomicon submit

Hints

  1. Each log line is ip method path status, separated by single spaces. cut -d " " -f 4 keeps just the status, and grep -c counts matching lines.
  2. For the top three, cut the first field, then sort, uniq -c, sort -nr, and head -n 3. Do the 500 count in one command and the top three in a second command.
  3. Line 1: cut -d " " -f 4 testdata/access.log | grep -c 500. Line 2: cut -d " " -f 1 testdata/access.log | sort | uniq -c | sort -nr | head -n 3.

Something wrong with this lesson? Report a problem