Skip to main content

Module 3: Text Processing & Search

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

3. Sort the Contents of a File

Pro TecMint Β· Root Plan
This Article is for Root Members
Join Root to read the full article and unlock everything

Full Access to Every Article, Course & Certification Track

Join thousands of Linux professionals who use Pro TecMint to advance their careers.

Ad-free access to all premium articles
All courses: Learn Linux, Bash, Golang, Ubuntu and more
RHCSA, RHCE, LFCS & LFCA certification prep
New courses added every month
Private Telegram community & priority support
Root Plan
$8/mo
or $59/year billed annually
Save $37 with annual plan
Start Reading This Article in the Next 60 Seconds
Join Root Plan β†’