sort reads lines, from files or from standard input, and writes them in order.
text
learner@tidepool:~$ sort names.txt
ana
ben
chenNumbers: -n
Without a flag, sort compares characters from the left, the same as words in a dictionary. For numbers, that gives a wrong order:
| Line | Order |
|---|---|
sort | 100, 12, 9 |
sort -n | 9, 12, 100 |
-n compares the lines as numbers.
Reverse: -r
-r reverses the order. sort -nr puts the largest number first.
A column: -k
Lines often have columns, separated by spaces. -k2 sorts on the second column:
text
learner@tidepool:~$ cat sales.txt
tea 3
cake 12
coffee 9
learner@tidepool:~$ sort -k2 -nr sales.txt
cake 12
coffee 9
tea 3cakecolumn 112column 2: sort on this
In a pipeline
sort is often in the middle or at the end of a pipeline:
text
learner@tidepool:~$ grep cake sales.txt | sort -k2 -n