Lesson 31: sort Command
In this lesson, you'll learn how to use the sort command to sort and print lines of text files in Linux.
to print lines from input text files and concatenatesort is a Linux program used to print lines from input text files and concatenate all files in sorted order.
It takes blank space as a field separator and the entire input file as the sort key. It is important to notice that the sort command doesn't actually sort the files, but only prints the sorted output unless you redirect the output.
Let's discuss some useful examples of the sort command.
sort Command Syntax
$ sort [OPTIONS] [FILE]
sort Command Options
| Option | Description |
|---|---|
-r |
Sort in reverse order |
-n |
Sort numerically instead of alphabetically |
-k N |
Sort by the Nth field/column |
-u |
Sort and remove duplicate lines |
-t DELIM |
Use DELIM as the field separator |
-o FILE |
Write output to a file instead of stdout |
1. Create a Sample File
First, we will be creating a text file (tecmint.txt) to execute sort command examples. Our working directory is /home/$USER/Desktop/tecmint.
The -e option in the below command enables the interpretation of backslash and \n tells echo to write each string to a new line.
$ echo -e "computer\nmouse\nLAPTOP\ndata\nRedHat\nlaptop\ndebian\nlaptop" > tecmint.txt
2. View the Contents of the File
Before we start with sort, let's have a look at the contents of the file and the way it looks.
$ cat tecmint.txt
computer
mouse
LAPTOP
data
RedHat
laptop
debian
laptop