sort Command in Linux
The Linux sort command is a simple yet powerful tool that allows you to sort lines in text files or streams. For organizing data, filtering log files, or cleaning up CSVs, sort is one of the most useful utilities in your command-line .
sort command Tutorial for DevOps : Organize and Analyze Text Data Easily
When working with logs, configuration files, or command output in Linux, organizing the data is often the first step. That’s where the sort command comes in. It's a simple yet powerful tool used to arrange lines of text in a specific order.
What is the sort Command ?
The sort command reads lines from a file or input stream and outputs them in sorted order.
Basic Syntax of sort Command :
sort [options] [file...]
If no file is specified, it reads from standard input.
Useful Options of sort Command
Option | Description |
---|---|
-n | Sort numerically |
-r | Reverse the sorting order |
-k N | Sort by the N-th column (field) |
-t CHAR | Use custom field delimiter (e.g., ,) |
-u | Remove duplicate lines (unique sort) |
-o FILE | Write output to a file |
-f | Ignore case when sorting |
--help | Show help page |
Example of sort Command
1. Simple Alphabetical Sort
sort names.txt
🔹 Sorts the lines in names.txt in ascending alphabetical order (A–Z).
2. Sort in Reverse Order
sort -r names.txt
🔹 Sorts lines in descending order (Z–A).
3. Numerical Sort
sort -n numbers.txt
🔹 Sorts based on numeric values rather than text order.
4. Sort by a Specific Column (Field)
sort -k 2 data.txt
🔹 Sorts using the second column (space-separated by default).
Practical use case of sort command
1. Case-Insensitive Sort
sort -f names.txt
🔹 Treats "A" and "a" as equal during sorting.
2. Remove Duplicate Lines
sort -u data.txt
🔹 Sorts and outputs only unique lines.
3. Save Sorted Output to a File
sort -n scores.txt -o sorted_scores.txt
🔹 Writes sorted output directly to sorted_scores.txt.
4. Sort and Count Duplicates (with uniq)
sort items.txt | uniq -c | sort -nr
🔹 Counts duplicate entries and sorts them by frequency.
5. Sort Disk Usage by Size
du -sh * | sort -h
🔹 Sorts human-readable sizes (-h handles K, M, G).
sort can structure, analyze, and clean data straight from the terminal.
Back​