Linux and Command-Line Basics
$ cat ips.txt
10.0.0.5
10.0.0.9
10.0.0.9
10.0.0.5
10.0.0.2
10.0.0.5
$ sort ips.txt | uniq -c | sort -nr | head -n 1The choices omit the leading spaces of the line. In the session above, which of the following is the line printed by the last pipeline?
- A1 10.0.0.2
- B2 10.0.0.9
- C3 10.0.0.5
Show answer and explanation
Answer: C. 3 10.0.0.5
sort arranges the lines so that identical lines are adjacent, and uniq -c merges adjacent identical lines and adds counts, giving the three lines 3 10.0.0.5, 2 10.0.0.9 and 1 10.0.0.2. sort -nr sorts by the leading number in descending order and head -n 1 takes the first line, so the output is 3 10.0.0.5. uniq merges only "adjacent" identical lines, so sorting first is essential. Chaining commands with pipes like this is a standard way to count the IP addresses with the most accesses, or the most frequent errors, in a log.
- A. Without -r on the last sort, the lines are in ascending order and the first is 1 10.0.0.2. -r sorts in descending order.
- B. This is the result of counting with uniq -c alone, without the first sort. uniq merges only adjacent lines, so only the two consecutive 10.0.0.9 lines are counted as 2.
- C. Correct. 10.0.0.5 appears most often, 3 times.