Skip to Content

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

OptionDescription
-nSort numerically
-rReverse the sorting order
-k NSort by the N-th column (field)
-t CHARUse custom field delimiter (e.g., ,)
-uRemove duplicate lines (unique sort)
-o FILEWrite output to a file
-fIgnore case when sorting
--helpShow 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​

Check out these tutorials :