
/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.
- 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
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.txtfor basic, reverse and unique sortingservices.tsvfor field, numeric and human-readable size sortingmonths.logfor month orderingversions.txtfor version orderingdeploy-a.loganddeploy-b.logfor merging already sorted files
Basic line sorting
Without options, sort compares each complete line and writes the ordered result to standard output.
sort names.txtTo save the result, use shell redirection:
sort names.txt > names.sorted.txtsort does not modify its input unless asked to write to an output file. GNU sort provides -o for this purpose:
sort -o names.sorted.txt names.txtUse -r to reverse the comparison order:
sort -r names.txtCommon options at a glance
| Option | Purpose |
|---|---|
-r | Reverse the chosen sort order |
-n | Compare numbers numerically |
-g | Compare general numeric values, including scientific notation |
-h | Compare human-readable sizes such as 512M and 1.5G |
-M | Compare month names such as Jan through Dec |
-V | Compare version-like strings naturally |
-k | Sort by a field or character range (a key) |
-t | Set a field separator |
-u | Keep one line for each equal sort key or line |
-f | Ignore case when comparing |
-b | Ignore leading blanks in keys |
-d | Use dictionary order: letters, digits and blanks only |
-s | Keep input order for records with equal keys |
-c | Check whether input is already sorted |
-m | Merge files that are already sorted |
-o FILE | Write 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:
- service name
- environment
- replica count
- memory limit
- release version
In Bash, $'\t' represents a tab character. Sort by replica count, smallest first:
sort -t $'\t' -k 3,3n services.tsvSort by the same field in descending order by adding r to the key modifier:
sort -t $'\t' -k 3,3nr services.tsvThese two forms are equivalent for this case:
sort -t $'\t' -n -k 3,3 services.tsv
sort -t $'\t' -k 3,3n services.tsvKeeping 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:
sort -g measurements.txtUse -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:
-k START,ENDField 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:
sort -t $'\t' -k 2,2 -k 3,3nr services.tsvA 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:
sort -t $'\t' -k 4,4h services.tsvReverse it to find the largest allocations first:
sort -t $'\t' -k 4,4hr services.tsvThis 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:
sort -f names.txtUse -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:
sort -u names.txtTo treat Alice and alice as duplicates as well, combine the options:
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:
sort -t $'\t' -k 2,2 -u services.tsvThat 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:
sort -b labels.txtDictionary order, -d, compares only letters, digits and blanks. Punctuation is ignored for comparison:
sort -d labels.txtThese 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:
sort -M -k 1,1 months.logTo sort newest month first:
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:
sort -V versions.txtFor descending releases:
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:
sort -s -t $'\t' -k 3,3n services.tsvThis is useful for multi-stage sorting. Sort by a secondary key first, then perform a stable sort by the primary key:
sort -t $'\t' -k 1,1 services.tsv | sort -s -t $'\t' -k 2,2For most cases, expressing both keys in one command is simpler:
sort -t $'\t' -k 2,2 -k 1,1 services.tsvCheck 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:
sort -o names.sorted.txt names.txt
sort -c names.sorted.txtWhen only the exit status matters in a script, GNU sort -C performs the same check quietly:
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:
sort -m -k 1,1 deploy-a.log deploy-b.logTo save the combined result:
sort -m -k 1,1 -o deployments.log deploy-a.log deploy-b.logThe 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:
find ./releases -type f -print0 | sort -z | xargs -0 -r ls -ldUse 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
-tand bounded keys such as-k 3,3for 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
-uonly when dropping duplicate records is intentional. - Use
-orather than redirecting to the same path as an input file. A shell opens redirected output beforesortreads its input. - Large sorts may use temporary files. GNU
sortsupports options such as-T DIRECTORYto choose temporary storage and-S SIZEto 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.
Comments and likes
Sign in or create an account to leave a comment or like this page.
0 comments
No comments yet.