How to Sort Text Files Using the sort Command in Linux

When you are auditing a massive Linux server log or formatting a 5,000-line chaotic text database, the raw data is often completely unorganized. If you need to quickly locate a specific server IP address or find an employee’s name in a massive list, manually scrolling through thousands of random lines is highly inefficient. To force the Linux kernel to mathematically analyze the file architecture and instantly restructure the entire dataset into perfect chronological or alphabetical order, you must use the sort command.

Executing an Alphabetical Sort

The standard sort command is an incredibly fast organizational engine. By default, it reads a file, mathematically evaluates the absolute first character on every single line, and violently restructures the file into strict alphabetical (A-Z) order.

Assume you have a chaotic file named employees.txt.

sort employees.txt

The exact millisecond you press Enter, the terminal output is perfectly organized. The engine does not modify the original file; it simply dumps the mathematically sorted data directly to your screen.

To execute a Reverse Alphabetical Sort (Z-A), you must inject the -r (reverse) flag.

sort -r employees.txt

Executing a Numerical Sort

The default engine is fundamentally flawed when dealing with pure numbers. Because it strictly looks at the first character, it will mathematically conclude that “100” comes before “2” (because 1 is less than 2). This causes catastrophic formatting errors.

To force the engine to read the data as actual mathematical integers, you must inject the -n (numerical) flag.

Assume you have a file named ip_addresses.txt.

sort -n ip_addresses.txt

The engine abandons alphabetical logic, mathematically calculates the total integer value of the numbers on each line, and outputs a perfectly structured list from lowest to highest.

Saving the Sorted Data

Because the sort engine only outputs to the terminal screen by default, the data is instantly lost when you close the window. To permanently capture the perfectly structured data, you must use a standard Linux redirect (>) to shove the output into a brand new file.

sort -n ip_addresses.txt > sorted_ips.txt

The engine executes the numerical sort and instantly writes the pristine data directly into the new sorted_ips.txt file, permanently locking the perfect structure into your hard drive.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.