Skip to main content

Mastering the `sort` Command in Linux

The sort command in Linux is an extremely useful utility for sorting lines in text files. Whether you need to organize data alphabetically, numerically, reverse the order, or even sort by specific column, sort has got you covered.

Syntax

The basic syntax of the sort command is:

sort [OPTION]... [FILE]...

Here, [OPTION] represents different ways you can sort your files, and [FILE] is one or more files that you want to sort. If no file is provided, sort will read from the standard input.

Options

Below is a table with some common options for the sort command:

OptionShorthandDescription
--ignore-leading-blanks-bIgnore leading blanks while sorting.
--dictionary-order-dSort in "phone book" order.
--ignore-case-fCase insensitive sorting.
--numeric-sort-nSort numerically.
--reverse-rReverse the result of comparisons.
--unique-uOnly print unique lines.
--check-cCheck for sorted order; do not sort.
--key=POS1[,POS2]-kSort by a specified key.
--version-sort-VNatural sort of (version) numbers within text.

Examples

Example 1: Simple Sorting

To create list.txt for this example:

echo -e "apple\norange\nbanana\napple" > list.txt

To sort the contents of a file named list.txt:

sort list.txt

Example 2: Sort Numerically

To sort numbers in a file numerically:

sort -n numbers.txt

To create numbers.txt for this example:

echo -e "8\n10\n1\n5" > numbers.txt

Example 3: Reverse Sorting

To sort a file in reverse order:

sort -r list.txt

Example 4: Unique Sorting

To sort a file and remove duplicates:

sort -u list.txt

Example 5: Check If Already Sorted

To check if a file is already sorted:

sort -c list.txt

Example 6: Case Insensitive Sorting

To perform a case-insensitive sort:

sort -f list.txt

Conclusion

The sort command is incredibly versatile and indispensable for text processing and data manipulation tasks in Linux. By learning to use its various options, you can handle the majority of sorting requirements with ease. Whether you're working with simple lists or complex datasets, sort will likely be one of the tools you reach for time and time again.

What Can You Do Next 🙏😊

If you liked the article, consider subscribing to Cloudaffle, my YouTube Channel, where I keep posting in-depth tutorials and all edutainment stuff for software developers.

YouTube @cloudaffle