Linux sort Command
The sort
command in Linux arranges lines in a file or input based on various criteria, such as alphabetical order, numerical order, and more. It’s commonly used for data processing, where sorting a file or output in a specific order is required.
Basic Syntax
Common Options
-r
: Sorts in reverse order.-n
: Sorts by numeric value.-k
: Specifies a column (or field) to sort by.-u
: Removes duplicate lines.-t
: Specifies a delimiter for sorting by fields (default is whitespace).
Examples with Output
Example 1: Sorting a File Alphabetically
Suppose file.txt
contains:
Command
Output
Explanation:
sort file.txt
arranges the lines alphabetically in ascending order.
Example 2: Sorting in Reverse Order
You can reverse the order of sorting using -r
.
Command
Output
Explanation:
sort -r file.txt
sorts the lines in reverse alphabetical order.
Example 3: Sorting Numerically
For files with numbers, use -n
to sort based on numeric values.
Suppose numbers.txt
contains:
Command
Output
Explanation:
sort -n
treats each line as a number, sorting numerically.
Example 4: Sorting by a Specific Column
Suppose data.txt
contains two columns of data separated by spaces:
Command
Output
Explanation:
-k 2
sorts based on the second column, which is the numeric values in this case.
Example 5: Sorting by a Delimited Field
If fields are separated by a specific delimiter, use -t
with -k
.
Suppose data.csv
contains:
Command
Output
Explanation:
-t ','
specifies a comma as the delimiter.-k 2
sorts by the second field, which is the numeric value after the comma.
Example 6: Removing Duplicate Lines
If a file has duplicate lines, -u
can remove them while sorting.
Suppose duplicates.txt
contains:
Command
Output
Explanation:
sort -u
removes duplicate lines, leaving only unique entries in sorted order.
Summary of Common sort
Commands
Command | Description |
---|---|
sort file.txt | Sorts lines alphabetically in ascending order. |
sort -r file.txt | Sorts lines in reverse alphabetical order. |
sort -n numbers.txt | Sorts lines numerically. |
sort -k 2 data.txt | Sorts by the second column (field) in whitespace-separated data. |
sort -t ',' -k 2 data.csv | Sorts by the second field in comma-separated data. |
sort -u duplicates.txt | Sorts and removes duplicate lines. |
The sort
command is an essential tool for organizing and managing data, particularly in scripts and data processing workflows.