Introduction
The sort command is one of the most used utilities in the Linux command line. It allows sorting lines of text quickly and efficiently, whether they come from a file, the output of another program, or standard input. Its operation is based on comparing the characters of each line according to the set of options indicated, making it an indispensable tool for processing logs, CSV files, user lists, and any other type of data structured as lines.
Although it seems simple at first glance, sort offers a large number of options that allow adapting its behavior to specific needs: numeric sorting, reverse, duplicate removal, sorting by specific columns, according to language, or even using a custom buffer size. Knowing these options helps write more efficient scripts and avoid unnecessary post‑processing.
Basic syntax
The simplest way to use sort is:
sort [options] file
If no file is specified, the command reads from standard input, allowing it to be combined with pipes (|) and redirections. By default, sort sorts in ascending order using lexicographic order based on ASCII or UTF‑8 code, depending on the environment configuration.
A quick example:
sort names.txt
This sorts the contents of names.txt alphabetically and displays the result on the screen.
Most used options
-n: sorts numerically, treating each line as a number. Ideal for lists of ages, scores, or IP addresses when you want 10 to come before 2.-r: reverses the output order, obtaining a descending list. It can be combined with-nto get the highest values first.-u: removes duplicate lines after sorting. Useful to obtain a unique set of values, for example, a user list without repetitions.-kfield: specifies the column or field on which to sort. You can indicate a range such as-k2,4to consider from the second to the fourth column.-tdelimiter: defines the character that separates fields. By default, any whitespace
This post is also available in ESPAÑOL.