Skip to content

sort Command in Linux

Summary

The sort command is a powerful tool in Linux for ordering lines of text in a file or from standard input. It can sort alphabetically, numerically, in reverse order, and based on specific fields within each line.

Introduction

The sort command reads lines from the specified input files or standard input, orders the lines according to the options provided, and writes the result to standard output. It's frequently used in pipelines to process and organize data for further analysis. By default, sort treats each line as a single field and sorts them in ascending ASCII collating sequence.

Use case and Examples

Basic Alphabetical Sorting

sort names.txt
This command sorts the lines in the names.txt file alphabetically and prints the sorted output to the terminal.

Sorting Numerically

sort -n numbers.txt
This command sorts the lines in the numbers.txt file numerically, treating each line as a number. This is especially useful when the file contains numbers as strings that need to be sorted in numerical order.

Sorting in Reverse Order

sort -r names.txt
This command sorts the lines in the names.txt file alphabetically in reverse order (descending).

Sorting by a Specific Field

sort -k 2 data.txt
This command sorts the lines in the data.txt file based on the second field (column), assuming the fields are separated by whitespace.

Sorting a piped command

ls -l | sort -k 5 -n
This command lists all files and directories in long listing format, then the output is piped to sort which sorts the results numerically based on the 5th field (file size).

Commonly used flags

Flag Description Example
-n Sort numerically sort -n numbers.txt Sorts the 'numbers.txt' file numerically.
-r Reverse the order of sorting sort -r names.txt Sorts the 'names.txt' file in reverse alphabetical order.
-k number Sort based on the specified column/field number. sort -k 2 data.txt Sorts the 'data.txt' file based on the second column.
-t separator Specify a character to use as a field separator. sort -t ':' -k 1 /etc/passwd Sorts the /etc/passwd file by the first field, using ':' as the separator.
-u Sorts uniquely, suppressing lines that repeat an earlier key. sort -u names.txt Sorts the 'names.txt' file and removes duplicate lines.
-f Treat upper and lower case as equivalent. sort -f names.txt Sorts 'names.txt' ignoring case.
-o file Write output to file instead of standard output. sort names.txt -o sorted_names.txt Sorts 'names.txt' and saves the result to 'sorted_names.txt'.


Share on Share on

Comments