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 1

The choices omit the leading spaces of the line. In the session above, which of the following is the line printed by the last pipeline?

  1. A1 10.0.0.2
  2. B2 10.0.0.9
  3. 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.
Practice this topic Back to topic

Books on Linux and Command-Line Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More Linux and Command-Line Basics questions

  1. You want to keep showing lines on the screen as they are appended later to the server log file /var/log/app.log. Which of the following commands is appropriate?
  2. Which of the following is the output of the command above, which extracts columns from a comma-separated line?
  3. Which of the following is the output of the sed command above, which replaces characters?
  4. In the session above, which of the following is printed by the last awk?
  5. Which of the following describes the files found when find /data -name "*.log" -mtime +7 -size +100M is run with GNU find?