Linux: Sort Lines

By Xah Lee. Date: . Last updated: .

This page shows how to sort lines in a file using linux shell command.

Here's basic examples:

sort fileName
Sort lines of a file. Comparison done as string.
sort -n fileName
Sort by considering beginning of lines as numbers.
sort -k n fileName
Sort by n th column.
By default, space or tab is used as delimitor for columns. Use option -t for different separator. For example sort -t ',' -k 2n myFile
sort -r fileName
Decending sort

Examples to sort by nth column:

# sort by 2nd column. Comparison done as string
sort -k 2 myFile

# sort by 2nd column, and preserve original order if 2nd column are same
sort -s -k 2 myFile

# sort by 2nd column, Comparison done as number. Preserve original order if possible.
sort -s -k 2n myFile

Here's a more complex example:

# decending sort by 2nd column as string, if tie, sort by 3rd column as number.
sort -k 2r -k 3n myFile