In Unix-like operating systems, sort is a standard command line program that prints the lines of its input or concatenation of all files listed in its argument list in sorted order. Sorting is done based on one or more sort keys extracted from each line of input. By default, the entire input is taken as sort key. Blank space is the default field separator.
The "-r" flag will reverse the sort order.
Sort was part of Version 1 Unix. By Version 4 Ken Thompson had modified it to use pipes, but sort retained an option to name the output file because it was used to sort a file in place. In Version 5, Thompson invented "-" to represent standard input.
The -n
option makes the program sort according to numerical value. The du command produces output that starts with a number, the file size, so its output can be piped to sort to produce a list of files sorted by (ascending) file size:
Use the -k
option to sort on a certain column. For example, use "-k 2
" to sort on the second column). In old versions of sort, the +1
option made the program sort on the second column of data (+2
for the third, etc.). This usage is deprecated.
The -k m,n
option lets you sort on a key that is potentially composed of multiple fields (start at column m
, end at column n
):
Here the first sort is done using column 2. -k2,2
specifies sorting on the key starting and ending with column 2. If -k2
is used instead, the sort key would begin at column 2 and extend to the end of the line, spanning all the fields in between. The n
stands for 'numeric ordering'. -k1,1
dictates breaking ties using the value in column 1, sorting alphabetically by default. Note that bob, an and chad have the same quota and are sorted alphabetically in the final output.
Sorting a file with tab separated values requires a tab character to be specified as the column delimiter. This illustration uses the shell's dollar-quote notation to specify the tab as a C escape sequence.