Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Using sort - Command Line Tutorial

Introduction

The sort command in Unix/Linux is a powerful utility that allows users to sort lines of text files. It is often used in conjunction with other commands through piping. In this tutorial, we will explore various ways to use the sort command with practical examples.

Basic Usage

The simplest usage of the sort command is to sort a file alphabetically. For example, if we have a text file named example.txt:

cat example.txt

banana
apple
cherry

We can sort this file using:

sort example.txt

apple
banana
cherry

Sorting in Reverse Order

To sort the contents of a file in reverse order, use the -r option:

sort -r example.txt

cherry
banana
apple

Sorting Numerically

By default, sort performs a lexical sort. To sort numerically, use the -n option. Consider the file numbers.txt:

cat numbers.txt

10
2
33

Sorting this file numerically:

sort -n numbers.txt

2
10
33

Sorting by a Specific Field

To sort by a specific field or column, use the -k option. For example, consider data.txt:

cat data.txt

1 apple
3 cherry
2 banana

To sort by the second field:

sort -k 2 data.txt

1 apple
2 banana
3 cherry

Sorting with Multiple Keys

To sort by multiple keys, use multiple -k options. Consider multidata.txt:

cat multidata.txt

1 apple 10
3 cherry 5
2 banana 5

To sort first by the third field and then by the second field:

sort -k 3,3 -k 2,2 multidata.txt

2 banana 5
3 cherry 5
1 apple 10

Sorting with Unique Keys

To sort and remove duplicate lines, use the -u option:

sort -u duplicate.txt

apple
banana
cherry

Handling Blank Lines

By default, sort treats blank lines as the smallest possible value. To ignore blank lines, use the -b option:

sort -b blanks.txt

apple
banana
cherry

Conclusion

The sort command is a versatile and powerful tool for ordering text data. Whether you need to sort alphabetically, numerically, or by specific fields, sort has you covered. Experiment with the different options to get the most out of this command.