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

Shell Basics

  1. Get System Info
  2. Shell Basics
  3. grep, cat, awk, uniq
  4. sort
  5. find, xargs
  6. diff Files/Dir
  7. dir size: du
  8. dir tree
  9. tar gzip bzip2 xz 7zip rar zip
  10. wget, curl, GET, HEAD
  11. rsync
  12. Install Packages

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