sort: Sort Lines of Text Files
August 12th, 2024 2:01 PM Mr. Q Categories: Command
Description:
The sort
command sorts lines of text files in ascending or descending order based on specified criteria. By default, it sorts lines alphabetically.
Command:
sort [options] file
Sample Input
file.txt
:
apple
orange
banana
grape
Sample Output (Default Sorting):
apple
banana
grape
orange
Options:
-r
: Sort in reverse order.-n
: Sort numerically (useful for sorting numbers).-k
: Sort based on a specific field or column.-u
: Output only unique lines.-t
: Specify a delimiter for fields (used with-k
).
Example with -r
Option:
To sort lines in reverse order:
sort -r file.txt
Sample Output with -r
:
orange
grape
banana
apple
Example with -n
Option:
To sort numerically (useful when sorting numeric data):
sort -n numbers.txt
Sample Input numbers.txt
:
10
2
33
22
Sample Output with -n
:
2
10
22
33
Example with -k
Option:
To sort based on a specific field, you need to specify the delimiter and field:
sort -t, -k2 file.csv
Sample Input file.csv
:
John,30
Alice,25
Bob,28
Sample Output with -t, -k2
:
Alice,25
Bob,28
John,30
Example with -u
Option:
To sort and remove duplicate lines:
sort -u file.txt
Sample Output with -u
:
apple
banana
grape
orange
Example with -t
Option:
To specify a delimiter (for sorting CSV or tab-delimited files):
sort -t$'\t' -k1 file.tsv
Sample Input file.tsv
:
apple\t2
banana\t1
orange\t3
Sample Output with -t$'\t' -k1
:
apple\t2
banana\t1
orange\t3
The sort
command is highly versatile and useful for organizing text data in a meaningful way.