The sort command

This command sorts the contents of a text file, line by line. The options are as follows:

  • -n: Sorts as per the numeric value
  • -d: Sorts as per the dictionary meaning
  • -h: Compares as per the human-readable numbers (for example, 1K 2G)
  • -r: Sorts in the reverse order
  • -t: Option to specify a delimiter for fields
  • +num: Specifies sort field numbers
  • -knum: Specifies sort field numbers
  • $ sort -k4 sample.txt: This will sort according to the fourth field
Sr Examples of command usage Explanation
1 sort sample.txt Alphabetically sorts the lines
2 sort -u sample.txt Duplicate entries are sorted
3 sort -r sample.txt Reverse sort
4 sort -n -k3 sample.txt Numerical sort of the third field

Get Learning Linux Shell Scripting - Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.