The sort command in Linux organizes lines of text in a file or input stream alphabetically, numerically, or based on custom rules. It’s essential for sorting data, removing duplicates, and preparing inputs for further processing.
Contents
- Sort Alphabetically (Default)
- Sort Numerically
- Reverse the Sort Order
- Sort by a Specific Field (Column)
- Sort and Remove Duplicates
- Sort Human-Readable Numbers (e.g., 2K, 1G)
- Case-Insensitive Sort
- Sort by Month Names
- Merge Already-Sorted Files
- Check if a File is Sorted
- Sort Using a Custom Delimiter
- Sort and Save Output to a New File
- Sort with a Custom Key (e.g., IP Addresses)
- Sort by String Length
- Combine with uniq for Frequency Counting
- Sort a File and Save the Output
- Sort with Delimiters (Custom Column Separator)
Sort Alphabetically (Default)
sort names.txt
Sorts lines in names.txt in ascending alphabetical order.
Sort Numerically
sort -n numbers.txt
-nsorts lines as numbers (e.g.,10comes after2).
Reverse the Sort Order
sort -r data.txt
-rsorts in descending order (reverse).
Sort by a Specific Field (Column)
sort -k2 employees.csv
-k2sorts by the second field (column) in a CSV file.
Sort and Remove Duplicates
sort -u duplicates.txt
-uoutputs only unique lines (removes duplicates).
Sort Human-Readable Numbers (e.g., 2K, 1G)
sort -h sizes.txt
-hinterprets suffixes likeK(kilo),M(mega), etc.
Case-Insensitive Sort
sort -f mixed_case.txt
-fignores case (e.g.,Appleandappleare treated equally).
Sort by Month Names
sort -M months.txt
-Msorts by month abbreviations (e.g.,Jan,Feb, etc.).
Merge Already-Sorted Files
sort -m file1.txt file2.txt
-mmerges pre-sorted files without re-sorting.
Check if a File is Sorted
sort -c data.txt
-cchecks if the file is sorted; exits with an error if not.
Sort Using a Custom Delimiter
sort -t',' -k3 sales.csv
-t','uses comma as the delimiter.-k3sorts by the third field.
Sort and Save Output to a New File
sort input.txt -o sorted.txt
-owrites the sorted output tosorted.txt.
Sort with a Custom Key (e.g., IP Addresses)
sort -t. -k1,1n -k2,2n -k3,3n -k4,4n ips.txt
Sorts IP addresses numerically by each octet.
Sort by String Length
awk '{ print length, $0 }' text.txt | sort -n | cut -d' ' -f2-
- Uses
awkto prepend line lengths, sorts numerically, then removes lengths.
Combine with uniq for Frequency Counting
sort log.txt | uniq -c
- Counts occurrences of each line after sorting.
Sort a File and Save the Output
sort file.txt > sorted_file.txt
Sorts file.txt and saves the result in sorted_file.txt.
Sort with Delimiters (Custom Column Separator)
sort -t: -k2 file.txt
Uses : as the field separator and sorts based on the second column.
Key Notes:
- Delimiters: Use
-tto specify field separators (e.g.,-t':'for colon-delimited files). - Stability: Use
-sfor stable sorting (preserves original order for equal keys). - Performance: For large files, use
-S SIZEto adjust memory usage (e.g.,-S 50%).
