sort
Text processing
Usage
sort -k 2 -n [file]Sorts lines; without -n it compares them as text so 10 comes before 9, and the locale decides the order unless you put LC_ALL=C in front.
Common flags
| Flag | Meaning |
|---|---|
| -n | Compare as numbers, not as text |
| -h | Compare human sizes such as 2K and 1G |
| -r | Reverse the order |
| -k | Sort by a field, as in -k2 |
| -t | Set the field separator |
| -u | Drop duplicate lines |
| -f | Ignore case |
| -o | Write the result to a file, even back onto the input |
Examples
du -sh * | sort -hBiggest directory last.
sort -t, -k2 -n data.csvNumeric sort on the second column.
sort -u names.txtSorted, with duplicates gone.
These were built to be piped together. Three joined commands are usually shorter than one that does everything.
How to read this
- Square brackets [ ] mark a part you may leave out.
- An ellipsis … means you can list more than one.
- Flags are case-sensitive — in some commands -r and -R do different things.
Questions
Q. What does sort do?
Sorts lines; without -n it compares them as text so 10 comes before 9, and the locale decides the order unless you put LC_ALL=C in front.
Q. How do I type it?
sort -k 2 -n [file] — square brackets mark the parts you can leave out.
Q. How many flags are worth knowing?
8 are listed here; the full set is in man sort. This command sits under Text processing.
Related commands
man page: man sort