The main utility for sorting lines of text files is sort. In this tutorial you will learn all the posibilities of this command.

When using sort you can specify a file or, more commonly, pipe the output of another command.

sort file.txt
ls | sort

Parameters

  • -n: numeric sort.
  • -r: reverse the sorting.
  • -h: sort human-readable numbers like 1K or 2M.
  • -u: show only the first instance of every value (not the repeated ones).
  • -k <start[,stop]>: sort by a column. This parameter allows specifying the ordering type for the start and stop position (see man page).
    # sort files by size
    ls -l | sort -k 5,5 -nr
    
    # sort logins (from last 24 hours) from oldest to newest
    lastlog -t 1 | sort -k 6,6n -k 7
    
  • -t '<character>': specify a field separator.
    sort -t ',' -k 2,2 -nr test.csv
    
Test with this online terminal:

If you have any suggestion, feel free to contact me via social media or email.