When working in the Linux terminal, you will frequently encounter messy, unsorted text files. Whether you are looking at a raw list of employee names, an unsorted database export, or a massive log file filled with IP addresses, trying to find information in a disorganized list is incredibly tedious. Instead of exporting the file to a graphical spreadsheet program, you can instantly organize the data directly in the terminal using the powerful sort command.
How to Sort Alphabetically
The basic sort command assumes you are dealing with text and organizes everything in standard alphabetical order (A to Z).
If you have a file named names.txt, simply open your terminal and type:
sort names.txt
The terminal will instantly print the contents of the file to the screen, perfectly alphabetized. (Note: The default sort command does not modify the original file; it merely prints the sorted output to your display).
How to Sort in Reverse Order
If you need the list organized from Z to A, you can use the -r (reverse) flag.
sort -r names.txt
The Numerical Sorting Trap
The most common mistake beginners make with the sort command is trying to sort numbers using the default settings. Because the default behavior treats everything as a text string, sorting the numbers 1, 2, and 10 will result in an order of: 1, 10, 2. (Because the text character “1” comes before “2”).
To tell Linux to treat the data as actual math values, you must use the -n (numerical) flag.
sort -n expenses.txt
This ensures that a line starting with 10 correctly appears after a line starting with 2.
How to Save the Sorted Results
Because sort only prints to the screen, you will likely want to save the organized data into a new, clean file. You do this using the standard Linux redirect operator (>).
sort -n expenses.txt > sorted_expenses.txt
This command silently organizes the data numerically and saves the perfect list into a brand-new file, leaving your messy original file untouched as a backup.