Master the Linux ‘sort’ Command: A Comprehensive Guide

Peter Hou
2 min readMay 20, 2023

--

This guide offers a deep dive into the ‘sort’ command in Linux, covering everything from its history and when to use it, to its parameters and use cases. Mastering ‘sort’ will enable you to handle large text files with ease, enhancing your efficiency in data analysis or system administration tasks. The guide is intended for anyone who wants to gain a thorough understanding of the ‘sort’ command and make the most of its capabilities.

Instructions

This article provides a detailed introduction to the ‘sort’ command in Linux. As an essential tool in the Linux environment, ‘sort’ can help us manage and process data more efficiently. From basic usage to various parameters, you will get a comprehensive understanding of ‘sort’ through this guide.

History

The ‘sort’ command was included in the earliest versions of UNIX and has been a part of the Linux operating system since its inception.

When and why to use it

The ‘sort’ command is primarily used to sort the contents of a text file line by line. If you are dealing with data analysis or system administration tasks, ‘sort’ can be extremely useful for organizing data and text in a meaningful way.

How to use it

The basic usage of the ‘sort’ command is quite straightforward. To sort a file, simply use the command ‘sort’ followed by the file name.

sort filename.txt

The commonly used parameters

‘sort’ has a number of parameters that can greatly enhance its functionality:

  • -r This parameter is used for reversing the result of comparisons.
sort -r filename.txt
  • -n This option sorts the file considering the line contents as numbers.
sort -n filename.txt

Other supported parameters

There are several other parameters available with the ‘sort’ command, such as -u for removing duplicates, -k for sorting by a key, -b for ignoring leading blanks, etc.

Most common use cases

One of the most common use cases of ‘sort’ command is sorting a file containing numerical data. Another common use case is to combine ‘sort’ with ‘uniq’ command to remove duplicate lines from a file.

sort filename.txt | uniq

The tricky skills

One of the tricky ways to use ‘sort’ command is to sort by specific columns or fields when dealing with CSV or similar file formats. You can do this using the -k option.

sort -t, -k2 filename.csv

What needs to be noted

The ‘sort’ command in Linux is case-sensitive by default. This means that uppercase and lowercase letters are treated differently.

Conclusion

The ‘sort’ command is an extremely powerful tool in the Linux ecosystem. With its various parameters and flexible use cases, it becomes an indispensable tool for anyone dealing with large amounts of text or data on a regular basis.

--

--

Peter Hou
Peter Hou

Written by Peter Hou

I am a Senior Software Engineer and tech lead in a top tech company.

No responses yet