How to Sort Files Based on Sizes in Linux

The sort command in Linux is used to arrange lines of text in a specified order.

Alby Andersen

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.

Sort Alphabetically (Default)

sort names.txt  


Sorts lines in names.txt in ascending alphabetical order.


Sort Numerically

sort -n numbers.txt  
  • -n sorts lines as numbers (e.g., 10 comes after 2).

Reverse the Sort Order

sort -r data.txt  
  • -r sorts in descending order (reverse).

Sort by a Specific Field (Column)

sort -k2 employees.csv  
  • -k2 sorts by the second field (column) in a CSV file.

Sort and Remove Duplicates

sort -u duplicates.txt  
  • -u outputs only unique lines (removes duplicates).

Sort Human-Readable Numbers (e.g., 2K, 1G)

sort -h sizes.txt  
  • -h interprets suffixes like K (kilo), M (mega), etc.

Case-Insensitive Sort

sort -f mixed_case.txt  
  • -f ignores case (e.g., Apple and apple are treated equally).

Sort by Month Names

sort -M months.txt  
  • -M sorts by month abbreviations (e.g., Jan, Feb, etc.).

Merge Already-Sorted Files

sort -m file1.txt file2.txt  
  • -m merges pre-sorted files without re-sorting.

Check if a File is Sorted

sort -c data.txt  
  • -c checks 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.
  • -k3 sorts by the third field.

Sort and Save Output to a New File

sort input.txt -o sorted.txt  
  • -o writes the sorted output to sorted.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 awk to 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 -t to specify field separators (e.g., -t':' for colon-delimited files).
  • Stability: Use -s for stable sorting (preserves original order for equal keys).
  • Performance: For large files, use -S SIZE to adjust memory usage (e.g., -S 50%).
Share This Article