/articles/linux-sort-command-practical-examples-and-common-options-6fdef060

Linux sort command: practical examples and common options

Use Linux sort to order text files by whole lines or selected fields, handle numbers, sizes, months and versions, remove duplicates, validate sorted input and merge pre-sorted files.

This article includes a quiz at the end. Sign in or create an account to access it, build your score, and unlock hall-of-fame badges.

Article assets6

Sign in or create an account to download article assets. Newsletter subscribers also get free access to cheat sheets.

Sign inCreate account
  • deploy-a.logtext/plain
  • deploy-b.logtext/plain
  • months.logtext/plain
  • names.txttext/plain
  • services.tsvtext/tab-separated-values
  • versions.txttext/plain

Browser terminal

Sign in to use this lab

Sign inCreate account

Linux sort command: practical examples and common options

sort orders lines from one or more text files. It is often used between commands in a pipeline, but it is just as useful for TSV exports, logs, package lists and generated reports.

One important detail first though: collation is locale-dependent. That is, the same text can sort differently on machines with different locale settings, particularly for case and non-ASCII characters. For reproducible byte-wise ordering in scripts, LC_ALL=C is the usual environment setting. It is deliberately not used in the examples below so the focus remains on sort itself.

Download these example files before running the commands:

  • names.txt for basic, reverse and unique sorting
  • services.tsv for field, numeric and human-readable size sorting
  • months.log for month ordering
  • versions.txt for version ordering
  • deploy-a.log and deploy-b.log for merging already sorted files

Basic line sorting

Without options, sort compares each complete line and writes the ordered result to standard output.

Bash
sort names.txt

To save the result, use shell redirection:

Bash
sort names.txt > names.sorted.txt

sort does not modify its input unless asked to write to an output file. GNU sort provides -o for this purpose:

Bash
sort -o names.sorted.txt names.txt

Use -r to reverse the comparison order:

Bash
sort -r names.txt

Common options at a glance

OptionPurpose
-rReverse the chosen sort order
-nCompare numbers numerically
-gCompare general numeric values, including scientific notation
-hCompare human-readable sizes such as 512M and 1.5G
-MCompare month names such as Jan through Dec
-VCompare version-like strings naturally
-kSort by a field or character range (a key)
-tSet a field separator
-uKeep one line for each equal sort key or line
-fIgnore case when comparing
-bIgnore leading blanks in keys
-dUse dictionary order: letters, digits and blanks only
-sKeep input order for records with equal keys
-cCheck whether input is already sorted
-mMerge files that are already sorted
-o FILEWrite output directly to FILE

The -h, -V, -g and some long options are GNU sort features. They are available on common Linux distributions, but may not exist in the sort supplied by every Unix-like system.

Numeric sorting with -n

Text comparison does not produce numeric order. For example, as text, 12 sorts before 3 because 1 comes before 3. Use -n when the selected values are ordinary numbers.

services.tsv is tab-separated and has these columns:

  1. service name
  2. environment
  3. replica count
  4. memory limit
  5. release version

In Bash, $'\t' represents a tab character. Sort by replica count, smallest first:

Bash
sort -t $'\t' -k 3,3n services.tsv

Sort by the same field in descending order by adding r to the key modifier:

Bash
sort -t $'\t' -k 3,3nr services.tsv

These two forms are equivalent for this case:

Bash
sort -t $'\t' -n -k 3,3 services.tsv
sort -t $'\t' -k 3,3n services.tsv

Keeping the modifier on the key is usually clearer when a command has multiple sort keys.

For values such as 1e6, -3.14 or other floating-point forms, GNU sort -g uses general numeric comparison:

Bash
sort -g measurements.txt

Use -n for simple integer and decimal columns; it is normally the more predictable choice for tabular operational data.

Sort a delimited file by a field with -t and -k

By default, fields are separated by runs of blanks. For CSV, TSV, colon-delimited and similar files, specify the actual separator with -t.

The key form is:

TEXT
-k START,END

Field numbering starts at one. -k 3,3 means “use only field three”. If the end position is omitted, the key continues through the rest of the line, which can create unexpected ties or ordering. Prefer an explicit end field for structured data.

Sort services.tsv by environment, then by replica count from largest to smallest within each environment:

Bash
sort -t $'\t' -k 2,2 -k 3,3nr services.tsv

A sort key can also begin at a character offset. For example, -k 2.2,2.2 means the second character of field two. This is useful occasionally, but named or cleanly separated fields are easier to maintain than character-position tricks.

Sorting memory sizes with -h

Human-readable limits cannot be sorted correctly as ordinary text or as plain numbers. 128M, 768M, 1.5G and 12G need unit-aware comparison.

GNU sort -h understands common suffixes and compares their values:

Bash
sort -t $'\t' -k 4,4h services.tsv

Reverse it to find the largest allocations first:

Bash
sort -t $'\t' -k 4,4hr services.tsv

This is particularly useful with output from tools that deliberately print abbreviated sizes, such as disk and memory reports.

Case-insensitive sorting and unique lines

sort -f folds case during comparison:

Bash
sort -f names.txt

Use -u to output one representative of each equal line. This is the standard replacement for the less reliable sort file | uniq pattern when all that is required is a sorted distinct list:

Bash
sort -u names.txt

To treat Alice and alice as duplicates as well, combine the options:

Bash
sort -f -u names.txt

-u applies to the selected sort key. For example, this keeps one row per environment rather than one completely distinct TSV row:

Bash
sort -t $'\t' -k 2,2 -u services.tsv

That command is useful for extracting a sorted list of values, but it discards the other rows. For a report where every row matters, use a complete key instead.

Ignoring leading whitespace and dictionary order

Leading spaces are common in manually maintained lists and command output. -b ignores leading blanks at the start of a key:

Bash
sort -b labels.txt

Dictionary order, -d, compares only letters, digits and blanks. Punctuation is ignored for comparison:

Bash
sort -d labels.txt

These are comparison rules, not text-cleaning operations. The original lines are still written unchanged. If the data must be normalised, clean it before sorting with an appropriate tool such as sed, awk or application code.

Sorting months with -M

Logs and reports sometimes use three-letter month names. Alphabetical order is not calendar order, so use -M.

The first field of months.log is a month abbreviation:

Bash
sort -M -k 1,1 months.log

To sort newest month first:

Bash
sort -M -r -k 1,1 months.log

-M compares recognised month names from Jan to Dec. For machine-readable dates, an ISO 8601 date such as 2025-03-02 already sorts correctly as text when the year, month and day have fixed widths.

Sorting software versions with -V

Version strings are another case where lexical order is misleading: 1.10.0 would otherwise come before 1.9.0.

Use GNU version sort:

Bash
sort -V versions.txt

For descending releases:

Bash
sort -V -r versions.txt

-V is intended for version-like text. It is useful for package tags, release names and image labels, but it does not replace semantic-version policy in deployment tooling. Pre-release identifiers and vendor-specific version conventions should still be tested against real input.

Keep equal records in their original order with -s

When several lines have the same selected key, sort can use the rest of each line as a final tie-breaker. If preserving the incoming order of equal keys matters, use stable sorting:

Bash
sort -s -t $'\t' -k 3,3n services.tsv

This is useful for multi-stage sorting. Sort by a secondary key first, then perform a stable sort by the primary key:

Bash
sort -t $'\t' -k 1,1 services.tsv | sort -s -t $'\t' -k 2,2

For most cases, expressing both keys in one command is simpler:

Bash
sort -t $'\t' -k 2,2 -k 1,1 services.tsv

Check sorted input with -c

sort -c checks whether a file is already ordered according to the selected comparison rules. It produces no sorted output; it returns a non-zero exit status and reports the first disorder if the file is not sorted.

Create a sorted file, then validate it:

Bash
sort -o names.sorted.txt names.txt
sort -c names.sorted.txt

When only the exit status matters in a script, GNU sort -C performs the same check quietly:

Bash
sort -C names.sorted.txt && echo "names are sorted"

Always give -c and -C the same -t, -k, -n, -r and other comparison options used to create the file. A file can be sorted by one key and unsorted by another.

Merge sorted files with -m

sort -m merges inputs that have already been sorted. It avoids re-sorting every record and is useful for rotated report fragments or batches produced independently.

Both deploy-a.log and deploy-b.log are already ordered by their first, ISO 8601 timestamp field. Merge them like this:

Bash
sort -m -k 1,1 deploy-a.log deploy-b.log

To save the combined result:

Bash
sort -m -k 1,1 -o deployments.log deploy-a.log deploy-b.log

The inputs must be sorted using compatible options. If one file was sorted in reverse order, or by a different key, -m will not repair it.

NUL-delimited filenames with -z

Filenames can contain spaces and newlines, so line-oriented pipelines are unsafe for arbitrary paths. GNU sort -z uses NUL characters as record separators and pairs with tools that support NUL-delimited output:

Bash
find ./releases -type f -print0 | sort -z | xargs -0 -r ls -ld

Use this pattern for filenames, not ordinary log or TSV data. The displayed output may still be difficult to read when filenames themselves contain control characters.

Practical notes for scripts

  • Quote file paths: sort "$input_file". This prevents the shell from splitting paths containing spaces.
  • Use -t and bounded keys such as -k 3,3 for structured data. Do not rely on default whitespace fields for CSV or TSV exports.
  • Put numeric, size, month or version modifiers on the relevant key when sorting several columns.
  • Use -u only when dropping duplicate records is intentional.
  • Use -o rather than redirecting to the same path as an input file. A shell opens redirected output before sort reads its input.
  • Large sorts may use temporary files. GNU sort supports options such as -T DIRECTORY to choose temporary storage and -S SIZE to set its memory buffer, but test those settings under the workload and filesystem constraints that apply to the host.

A dependable sort command is mostly about choosing the correct comparison rule and restricting it to the correct field. Once those two details are explicit, sorting shell data becomes predictable and easy to revie

Memory check locked

Sign in or create an account to take the quiz and earn badges.

Sign inCreate account

Comments and likes

0 likes

Sign in or create an account to leave a comment or like this page.

Sign inCreate account

0 comments

No comments yet.

Back to top