sort
Overview
The sort command sorts lines of text files or standard input. It provides various sorting options including numeric, alphabetic, and custom field-based sorting.
Syntax
sort [options] [file...]Common Options
| Option | Description |
|---|---|
-n |
Numeric sort |
-r |
Reverse order |
-u |
Unique lines only |
-f |
Ignore case |
-k field |
Sort by field |
-t char |
Field separator |
-o file |
Output to file |
-c |
Check if sorted |
-m |
Merge sorted files |
-s |
Stable sort |
-R |
Random sort |
-h |
Human numeric sort |
Sort Types
| Type | Description |
|---|---|
| Alphabetic | Default text sorting |
| Numeric | Numerical value sorting |
| Human | Human-readable numbers (1K, 2M) |
| Month | Month name sorting |
| Version | Version number sorting |
| Random | Random order |
Key Use Cases
- Sort text files
- Organize data
- Remove duplicates
- Prepare data for processing
- System administration tasks
Examples with Explanations
Example 1: Basic Sort
sort file.txtSorts lines alphabetically
Example 2: Numeric Sort
sort -n numbers.txtSorts numbers in numerical order
Example 3: Sort by Field
sort -k 2 -t ',' data.csvSorts CSV by second field
Field-Based Sorting
Specify fields using -k: - -k 2 - Sort by field 2 - -k 2,4 - Sort by fields 2 through 4 - -k 2n - Numeric sort on field 2 - -k 2r - Reverse sort on field 2
Common Usage Patterns
Remove duplicates:
sort -u file.txtSort and save:
sort file.txt -o sorted.txtMultiple field sort:
sort -k 1,1 -k 2n file.txt
Advanced Sorting
Case-insensitive:
sort -f file.txtReverse numeric:
sort -nr file.txtMonth sorting:
sort -M months.txt
Performance Analysis
- Memory usage increases with file size
- External sorting for large files
- Use
-Sto specify buffer size - Consider using
--parallelfor multi-core systems - Temporary files created for large sorts
Additional Resources
Best Practices
- Use appropriate sort type
- Specify field separators clearly
- Test with small datasets first
- Consider memory limitations
- Use stable sort when needed
Locale Considerations
- Sorting affected by locale settings
- Use
LC_ALL=Cfor consistent results - Consider character encoding
- Collation rules vary by locale
Troubleshooting
- Unexpected sort order
- Memory limitations
- Field separator issues
- Locale-related problems
- Large file handling
Integration Examples
With pipes:
cat file.txt | sort | uniqWith find:
find . -name "*.txt" | sortLog analysis:
sort -k 4 -t ' ' access.log