Skip to content

Linux sort command (sort data)

The sort command in Linux sorts the lines of a file. Once ordered, a file can be processed by other commands, such as removing duplicate occurrences with the uniq command.

Your options are:

  • -b: Ignore spaces at the beginning of the line;
  • -d: Put lines in alphabetical order and ignore punctuation;
  • -f: Ignore the difference between uppercase and lowercase letters;
  • -I: Ignore control characters;
  • -h: sort in human format
  • -m: Merge two or more files into an ordered output file; -M: Treat the first three letters of
  • the lines as month (e.g. JAN); -n: Sort by numbers at the beginning of the lines;
  • -r: Sort by the numbers at the beginning of the lines;
  • -r: Sort in reverse order;
  • -u: If the line is duplicated, it shows only the first line;
  • -o: Send the command output to the file.

As an example, let’s sort an email archive:

$ sort emails

[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]

Care must be taken when ordering numbers. See the example of the unordered file below:

$ cat numbers 330 40 4 3 31 19 1

When using sort without any parameters, it sorts first using the first byte, then the second:

$ sort numbers 1 19 3 31 330 4 40

To sort using numbers as characters, you can use the -n option, or the -h option to sort in human format:

$ sort -n numbers 1 3 4 19 31 40 330