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.
The basic syntax of the
sort command is:
sort [OPTION]... [FILE]...
[OPTION] represents different ways you can sort your files, and
is one or more files that you want to sort. If no file is provided,
read from the standard input.
Below is a table with some common options for the
|Ignore leading blanks while sorting.
|Sort in "phone book" order.
|Case insensitive sorting.
|Reverse the result of comparisons.
|Only print unique lines.
|Check for sorted order; do not sort.
|Sort by a specified key.
|Natural sort of (version) numbers within text.
Example 1: Simple Sorting
list.txt for this example:
echo -e "apple\norange\nbanana\napple" > list.txt
To sort the contents of a file named
Example 2: Sort Numerically
To sort numbers in a file numerically:
sort -n numbers.txt
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
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.