Bitpath

Boss lesson · Unit 02

The top talkers

Build sort | uniq -c | sort -rn | head over an access log, one stage at a time

12 exercisesabout 3 min

What you practise

  • Build cut | sort | uniq -c | sort -rn | head step by step over an access log
  • Why sort must come before uniq
  • xargs and tee

Try a question from this lesson

Pick one

Each line of access.log is one request: client address, method, path. To find the busiest client, what must you do with these lines?

10.0.0.2 GET /
10.0.0.3 GET /a
10.0.0.2 GET /b
10.0.0.1 GET /
10.0.0.2 POST /x
10.0.0.3 GET /

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

The counting idiom

sort | uniq -c is how the shell counts things. sort brings equal lines together, then uniq -c collapses each run into one line with its size in front.

You now have a tally, still in address order. Sort it by the count, largest first, and the top of the list is your answer.

$ cut -d ' ' -f 1 access.log |
    sort | uniq -c
      1 10.0.0.1
      3 10.0.0.2
      2 10.0.0.3

Concept

Two adapters: xargs and tee

Some commands ignore stdin and only look at their arguments: rm, mv, ls. xargs bridges the gap. It reads lines from stdin and hands them to a command as arguments.

tee is a T-junction. It copies stdin into a file and also passes it on, so you can save one stage of a pipeline without stopping it.

shell
ls *.log | xargs wc -l
# runs: wc -l a.log b.log

sort big.txt | tee sorted.txt | wc -l
# saves every line, prints the count

9 more exercises in the app

  • 4× type the answer
  • 2× multiple choice
  • 1× fill the blanks
  • 1× order the lines
  • 1× true or false

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy