← Linux and the Command Line
Lesson 21 of 51 · 10 XP
sort and uniq — sorting and counting
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
sort names.txt # in alphabetical order
sort -r names.txt # in reverse order
sort -n numbers.txt # as NUMBERS (otherwise 10 comes before 9)
sort -k2 -n table.txt # by the second column, numerically
sort -t, -k3 data.csv # the separator is a comma
sort -u names.txt # remove repeats
uniq removes neighbouring repeated lines, which is why sort almost always comes before it:
sort words.txt | uniq # unique lines
sort words.txt | uniq -c # with the number of repeats
sort words.txt | uniq -d # only those that repeat
The famous "top most frequent" pipe appears in every administrator's guide:
cut -d' ' -f1 access.log | sort | uniq -c | sort -rn | head -5 # the top 5 IP addresses
Task. The input is words, one per line. Print the three most frequent words in the format count word, from the most frequent to the least. A hint about the format: uniq -c pads the numbers with spaces on the left, and the check takes this into account.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.