Boss lesson · Unit 02
The top talkers
Build sort | uniq -c | sort -rn | head over an access log, one stage at a time
What you practise
- Build
cut | sort | uniq -c | sort -rn | headstep by step over an access log - Why
sortmust come beforeuniq xargsandtee
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 /Correct answer
Count how often each value in column 1 appears
Why
The busiest client is the address that appears most often, so you need column 1 and a tally per value. No single tool does that, but four small ones in a row do. Build it stage by stage.
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.3Concept
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.
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 count9 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.