sort is a very powerful utility in the Unix/Linux toolkit. It can sort on various criteria, it can check and merge sorted files, it can sort on different keys, and it can even sort on different characters within those keys. It can also strip out repetitions, which can eliminate the need for the sort file.txt | uniq syntax.

The switches for sort fall into two categories. There are switches that modify the behavior of sort; -u strips out duplicate results, and -c and -C only check whether or not the input is sorted. -t specifies a field separator other than whitespace, and -s leaves otherwise-equal lines in the order in which they were originally found in the input. The other switches modify the strategy that sort actually uses to sort its input. Table 13-1 summarizes the flags that sort can take to modify its sorting strategy.

Table 13-1: Sort Modifiers

Flag Result
-M Sort by month; unknown < Jan < Dec (depending on locale).
-b Ignore leading whitespace.
-d Dictionary sort; ignore punctuation.
-f Case-insensitive sort.
-g General numerical sort. Use -n for most purposes.
-i Ignore non-printable characters.
-h Sort human-readable filesizes.
-n Numerical sort; 9 before 10.
-R Random sort.
-r Reverse the results of the sort.
-V A sorting algorithm that understands that software version numbers often look like foo-1.23a.093.

The sort -M feature depends on the current locale, specifically the LC_TIME ...

Get Shell Scripting: Expert Recipes for Linux, Bash, and More now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.