When working with large data files, log files, or simple lists in the Ubuntu Linux terminal, you will frequently encounter unsorted data. Manually opening a file in a text editor to alphabetize hundreds of lines is tedious and inefficient. The Linux command line provides a powerful, dedicated utility specifically for this purpose: the sort command. This command takes the contents of a file, organizes the lines according to your specific rules, and outputs the cleanly sorted result directly to your terminal screen.
The Basic sort Command
By default, the command organizes lines alphabetically (from A to Z) based on the first character of each line.
Assume you have a file named employees.txt containing a random list of names. To sort this list alphabetically, you would open your terminal and type:
sort employees.txt
The system will instantly print the contents of the file in perfect alphabetical order. Note: The original employees.txt file is completely untouched. The command only changes the output displayed on your screen.
Saving the Sorted Output
If you want to permanently save the newly sorted list, you must use the standard Linux redirect operator (>) to push the output into a brand new file.
sort employees.txt > sorted_employees.txt
This command creates a new file called sorted_employees.txt containing the alphabetized data, leaving your original file safely intact as a backup.
Advanced Sorting Flags
Alphabetical sorting is just the beginning. You can append flags to the command to change the sorting behavior entirely.
Reverse Alphabetical Order
If you need the list sorted backward (from Z to A), use the -r (reverse) flag.
sort -r employees.txt
Sorting Numbers Numerically
If you have a file containing a list of numbers (e.g., 10, 2, 5, 100), the default alphabetical sort will fail. It looks at the first character, meaning it will sort “100” before “2” because 1 comes before 2. To force the command to evaluate the actual mathematical value of the numbers, use the -n (numeric) flag.
sort -n numbers.txt
Removing Duplicate Lines
If your list contains duplicate entries and you only want to see a clean list of unique items, you can use the -u (unique) flag. This will sort the list and automatically delete any identical repeating lines.
sort -u emails.txt