When you dump raw data from a massive database into a standard Linux text file—such as a list of 5,000 employee names or a log of 10,000 transaction amounts—that data is completely disorganized. You cannot easily find the highest transaction or quickly locate a specific employee if the text file is entirely random. To force the Linux kernel to instantly parse the raw data and mathematically reorder every single line into a perfect alphabetical or numerical hierarchy, you must use the sort command.
How the sort Command Works
The sort command is an aggressive reordering engine. When you execute it against a file, it reads the absolute first character of every single line, mathematically compares their ASCII values, and instantly rebuilds the entire file from top to bottom.
To execute a basic alphabetical sort on a file named employees.txt, simply type:
sort employees.txt
The terminal will instantly output the massive list to your screen, perfectly arranged from A to Z.
However, this output is strictly temporary; it only prints to your screen. The actual employees.txt file remains completely untouched and disorganized. To permanently write the mathematically sorted data into a brand new, clean text file, you must use the standard bash redirect operator (>):
sort employees.txt > sorted_employees.txt
Sorting by Numerical Values
The default sort engine is strictly alphabetical, which causes massive catastrophic errors if you attempt to sort numbers. Alphabetically, the number “100” comes before the number “2” because “1” is alphabetically lower than “2”.
To force the engine to completely abandon its alphabetical rules and execute a strict mathematical evaluation of the digits, you must append the -n (numerical) flag.
sort -n transaction_amounts.txt
The system will now perfectly arrange the lines from the lowest mathematical value to the absolute highest mathematical value.
Executing a Reverse Sort
If you are sorting a massive list of transaction amounts to find the absolute largest purchases, a standard numerical sort is incredibly annoying because the largest numbers will be buried at the absolute bottom of the file.
To force the engine to mathematically invert the entire list, placing the Z’s before the A’s, or the highest numbers before the lowest numbers, you must append the -r (reverse) flag.
sort -nr transaction_amounts.txt
This command combines the numerical (-n) and reverse (-r) flags, instantly outputting the file with the absolute highest transaction sitting perfectly at the top of your screen.