Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to sort lines of text files in Linux?
The sort command in Linux is used to arrange lines of text files in a specified order. By default, it sorts lines alphabetically in ascending order, but it offers numerous options to customize the sorting behavior based on different criteria such as numeric values, months, or reverse order.
Syntax
The general syntax of the sort command is as follows:
sort [OPTION]... [FILE]... sort [OPTION]... --files0-from=F
Common Sort Options
| Option | Description |
|---|---|
| -b, --ignore-leading-blanks | Ignore leading blanks when sorting |
| -d, --dictionary-order | Consider only blanks and alphanumeric characters |
| -f, --ignore-case | Perform case-insensitive sorting |
| -g, --general-numeric-sort | Compare according to general numerical value |
| -i, --ignore-nonprinting | Consider only printable characters |
| -M, --month-sort | Sort by month names (JAN < FEB < ... < DEC) |
| -h, --human-numeric-sort | Compare human-readable numbers (1K, 2M, 3G) |
| -n, --numeric-sort | Compare according to string numerical value |
| -r, --reverse | Reverse the result of comparisons |
| -u, --unique | Output only unique lines |
Examples
Basic Alphabetical Sorting
Create a sample file and sort it alphabetically:
$ cat > text.txt Sid Vikash Gaurav ^C $ sort text.txt Gaurav Sid Vikash
Reverse Sorting
Sort the file in reverse order using the -r option:
$ sort -r text.txt Vikash Sid Gaurav
Numeric Sorting
When sorting files containing numbers, use -n for proper numeric ordering:
$ cat > numbers.txt 100 2 30 $ sort -n numbers.txt 2 30 100
Case-Insensitive Sorting
Sort without considering case differences using -f:
$ cat > mixed.txt apple Banana cherry $ sort -f mixed.txt apple Banana cherry
Saving Sorted Output
Redirect the sorted output to a new file:
$ sort text.txt > sorted_text.txt
Sorting Multiple Files
Sort multiple files simultaneously:
$ sort file1.txt file2.txt file3.txt > combined_sorted.txt
Advanced Usage
Sorting by Specific Fields
Use -k to sort by specific columns or fields:
$ sort -k2 data.txt # Sort by second field $ sort -k1,1 -k2,2n data.txt # Sort by first field, then numerically by second
Removing Duplicates
Use -u to output only unique lines:
$ sort -u duplicates.txt
Getting Help and Version Information
To view all available options and detailed help:
$ sort --help
To check the version of the sort command:
$ sort --version
Conclusion
The sort command is a powerful utility for organizing text data in Linux systems. It provides flexible sorting options including alphabetical, numeric, reverse, and field-specific sorting. Understanding these options enables efficient text processing and data organization tasks in command-line environments.
