Linux: Sort Lines

By Xah Lee. Date:

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

Here's basic examples:

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

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

If you have a question, put $5 at patreon and message me.