Linux: Sort Lines

By Xah Lee. Date: . Last updated: .

Sort lines, as string

sort fileName

Sort lines, beginning of line as number

sort -n fileName

Sort lines, by nth column

sort -k n fileName

By default, space or tab is used as delimitor for columns. Use option -t for different separator. e.g. sort -t ',' -k 2n myFile

# 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

Decending sort

sort -r fileName

Example: complex sort

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

Linux, Process Text