Mastering the sort Command in Linux with Examples

The sort command is a powerful utility in Linux used to sort lines of text files in various ways. It can handle numerical, alphabetical, and even complex sorting operations with ease. This article explores how to use the sort command effectively, with practical examples.

Basic Syntax

The basic syntax of the sort command is:

sort [options] [file]

If no file is specified, sort reads from standard input.

Sorting Alphabetically

By default, sort arranges lines in ascending ASCII order.

Example:

cat names.txt
Alice
Bob
Charlie
Eve
David

sort names.txt
Alice
Bob
Charlie
David
Eve

Sorting Numerically

The -n option sorts numbers instead of treating them as text.

Example:

echo -e "10\n2\n30\n1" | sort -n
1
2
10
30

Sorting in Reverse Order

Use the -r option to reverse the order of sorting.

Example:

echo -e "apple\nbanana\ncherry" | sort -r
cherry
banana
apple

Sorting by a Specific Column

The -k option allows sorting based on a specific column in a file.

Example (Sorting by second column):

echo -e "John 25\nAlice 30\nBob 20" | sort -k2 -n
Bob 20
John 25
Alice 30

Sorting with Unique Values

To remove duplicates while sorting, use the -u option.

Example:

echo -e "apple\nbanana\napple\ncherry" | sort -u
apple
banana
cherry

Ignoring Case While Sorting

The -f option makes sorting case-insensitive.

Example:

echo -e "banana\nApple\ncherry" | sort -f
Apple
banana
cherry

Sorting by File Size (Human Readable)

If dealing with file sizes, use the -h option to handle human-readable formats (e.g., KB, MB, GB).

Example:

echo -e "10K\n1M\n500K" | sort -h
10K
500K
1M

Sorting Delimited Data

For files with a specific delimiter (e.g., CSV files), use -t to define the delimiter.

Example (Sorting by second field using : as a delimiter):

echo -e "Alice:3\nBob:1\nCharlie:2" | sort -t: -k2 -n
Bob:1
Charlie:2
Alice:3

Combining Multiple Sorting Options

You can combine multiple options for advanced sorting.

Example (Sorting numbers in descending order, ignoring case):

echo -e "apple\nBanana\ncherry" | sort -r -f
cherry
Banana
apple

Conclusion

The sort command is an essential tool for organizing data in Linux. With options for numerical sorting, column-based sorting, case-insensitive ordering, and more, it provides flexibility for handling various text processing tasks. Mastering these options can significantly enhance your command-line productivity!

Leave a Reply

Your email address will not be published. Required fields are marked *