Linux sort Command: Sorting Text File Lines in the Terminal
The sort command in Linux sorts the lines of a file. After sorting, a file can be processed by other commands, such as removing duplicate occurrences with the uniq command.
Its options are:
- -b: Ignores spaces at the beginning of the line;
- -d: Sorts lines alphabetically and ignores punctuation;
- -f: Ignores the difference between uppercase and lowercase;
- -I: Ignores control characters;
- -h: Sort in human-readable format
- -m: Merges two or more files into a sorted output file;
- -M: Treats the first three letters of lines as month (e.g., JAN);
- -n: Sorts by numbers at the beginning of lines;
- -r: Sorts in reverse order;
- -u: If the line is duplicated, shows only the first one;
- -o: Sends the command output to the file.
For example, let's sort an email file:
$ sort emails
[email protected]@[email protected]@[email protected]@[email protected]@empresa.com
One caution should be taken when sorting numbers. See the example of the unsorted file below:
$ cat numeros 330404331191
When using sort without any parameter, it sorts first using the first byte, then the second:
$ sort numeros 119331330440
To sort using numbers as characters, you can use the -n option, or the -h option to sort in human-readable format:
$ sort -n numeros 134193140330
Learn much more about Linux in our online course. You can enroll here. If you already have an account, or want to create one, just log in or create your user here.
Liked it? Share
That was just one piece. The course teaches the whole path — from your first command to exam day.