Website Vidya
Cloud & DevOpsStep-by-Step Guide

sort Command in Linux: Sort Lines of Text and Numerical Data

Learn sort command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
9 min read
PDF Cheat Sheet
sort Command in Linux: Sort Lines of Text and Numerical Data
AI Executive SummaryWebsiteVidya AI

9 min read

Learn sort command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What sort Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

Mastering the sort command in linux is essential for organizing, analyzing, and transforming structured text data across command-line environments. Standardized in POSIX and provided by GNU coreutils, sort reorganizes lines of text according to user-defined collation rules, handling everything from basic ASCII alphabetical ordering to complex multi-column numerical comparisons.

In Unix pipelines, sort frequently serves as the indispensable bridge between data generation and data aggregation. Utilities like uniq require sorted input to eliminate duplicate records, while reporting tools rely on sort to rank top-consuming processes, identify disk-heavy directories, and surface anomalous web traffic.

Beyond simple text ordering, GNU sort incorporates advanced sorting modes: human-readable numbers (-h, e.g. 2K, 4M, 1G), version numbers (-V), month names (-M), random shuffling (-R), and external merge sort capabilities that process multi-gigabyte datasets without exhausting system memory.

Advertisement
sort Command in Linux: Sort Lines of Text and Numerical Data — syntax, flags, and practical terminal workflow diagram
sort Command in Linux: Sort Lines of Text and Numerical Data — command syntax, key options, and production workflow reference.

What sort Does and When to Use It

At the architectural level, GNU coreutils sort uses an external merge sort algorithm. When sorting small datasets that fit into memory, sort utilizes an in-memory quicksort or introsort routine. However, when processing massive datasets that exceed the memory allocation threshold specified by -S (--buffer-size), sort partitions the input into temporary sorted chunks, writes them to temporary spill files in /tmp (or the path defined by -T), and merges the sorted runs using a k-way tournament tree.

Collation rules are heavily influenced by the active system locale: by default, sort honors the LC_COLLATE and LC_ALL environment variables. In UTF-8 locales (such as en_US.UTF-8), collation rules follow complex dictionary ordering that ignores certain punctuation and case differences. For deterministic, high-speed, byte-level ASCII sorting in shell scripts, administrators set LC_ALL=C, which bypasses locale lookup tables and boosts sort speed by 2x to 5x.

Under the hood, sort gathers runtime telemetry or dispatches control signals by reading virtual filesystems mounted at /proc and /sys, or by communicating with PID 1 (systemd) over D-Bus. Using flags such as -n, -r, -u, -k POS1[,POS2] turns raw process and service tables into actionable diagnostics during incident response.

Availability and Installation Across Linux Distributions

The sort utility is packaged in coreutils across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether sort is installed and inspect which binary path and version your shell resolves:

type -a sort
sort --version 2>/dev/null || man -f sort

# Illustrative output (reviewed against documentation)
sort is /usr/bin/sort
sort (coreutils)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y coreutils

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y coreutils

# Arch Linux
sudo pacman -S --noconfirm coreutils

# Alpine Linux
sudo apk add --no-cache coreutils

Command Syntax, Arguments, and Exit Status Codes

sort [OPTION]... [FILE]...

The syntax follows the structure sort [OPTION]... [FILE].... If multiple files are passed, sort reads and merges all of them into a single sorted output stream. If no FILE arguments are given or a hyphen (-) is supplied, sort reads from standard input (stdin).

Sorting keys are defined using the -k POSIX syntax: -k POS1[,POS2], where POS1 is the starting field and character offset, and POS2 is the optional ending field. The field delimiter is defined with -t (defaulting to transitions between non-whitespace and whitespace).

  • 0 — Successful execution; input successfully sorted and emitted.
  • 1 — Operational failure; file unreadable, or when -c is used, input was not sorted.
  • 2 — Command-line syntax error or invalid key specification.

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-n--numeric-sortCompare according to string numerical value (handles negative numbers and decimals).
-r--reverseReverse the result of comparisons (descending order).
-u--uniqueOutput only the first of an equal run (deduplicates sorted lines).
-k POS1[,POS2]--key=POS1[,POS2]Sort by a key defined by column positions POS1 through POS2.
-t SEP--field-separator=SEPUse character SEP as the field delimiter instead of whitespace.
-h--human-numeric-sortCompare human-readable numbers (e.g. 2K, 45M, 2G).
-V--version-sortNatural sort of version numbers within text (e.g. v1.2, v1.10).
-c--checkCheck whether input is already sorted; do not sort if ordered.
-S SIZE--buffer-size=SIZESet the maximum main memory buffer size (e.g. -S 2G).

A common trap in Linux administration is sorting numerical data without -n. In standard lexicographical sorting, '10' appears BEFORE '2' because the character '1' precedes '2' in the ASCII table. Passing -n guarantees proper mathematical comparison.

Advertisement

When sorting specific columns, always restrict the key range explicitly using -k 2,2 rather than -k 2. An open-ended key like -k 2 instructs sort to compare starting from column 2 all the way to the end of the line, which can distort results if trailing columns vary.

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. Basic Alphabetical Sorting of Text Lines

Sort a list of server hostnames alphabetically in ascending order.

cat << 'EOF' > hosts.txt
web-02
db-01
api-01
web-01
EOF
sort hosts.txt

# Illustrative output (reviewed against documentation)
api-01
db-01
web-01
web-02

sort orders lines alphabetically based on standard ASCII/locale collation.

2. Sort Numbers Mathematically with -n and Reverse Order with -r

Sort a list of process IDs or numeric port numbers in descending mathematical order.

printf "100\n2\n50\n1\n25\n" | sort -nr

# Illustrative output (reviewed against documentation)
100
50
25
2
1

The -n flag ensures 100 is evaluated as greater than 50, and -r reverses output into descending order.

3. Sort by Specific Column Using -t and -k

Sort /etc/passwd numerically by the third column (UID).

sort -t: -k3,3n /etc/passwd | head -n 4

# Illustrative output (reviewed against documentation)
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin

Setting -t: defines the colon delimiter, and -k3,3n restricts numerical sorting strictly to field 3.

4. Sort Human-Readable Storage Sizes with -h

Sort directory disk usage outputs from du -h in human-readable order (KB, MB, GB).

printf "1.2G\n450M\n2.5G\n12K\n" | sort -h

# Illustrative output (reviewed against documentation)
12K
450M
1.2G
2.5G

The -h flag parses metric and binary multipliers (K, M, G, T) to sort human-readable units accurately.

5. Sort Software Release Version Strings with -V

Sort application version tags naturally so version 1.10 appears after version 1.9.

printf "v1.9.0\nv1.10.0\nv1.2.1\nv1.20.0\n" | sort -V

# Illustrative output (reviewed against documentation)
v1.2.1
v1.9.0
v1.10.0
v1.20.0

The -V flag enables version sorting, treating multi-digit numbers within strings as numbers rather than characters.

6. Deduplicate Lines While Sorting Using -u

Sort an unsorted list of IP addresses and eliminate duplicate entries in a single step.

printf "192.168.1.1\n10.0.0.1\n192.168.1.1\n172.16.0.1\n" | sort -u

# Illustrative output (reviewed against documentation)
10.0.0.1
172.16.0.1
192.168.1.1

The -u flag suppresses duplicate keys, producing a sorted, unique list identical to piping into uniq.

Real-World Workflows, Pipelines, and Shell Automation

Disk Capacity Audit: Finding Largest Directories in /var

Identify the top 5 largest directories consuming storage space using du and sort.

#!/usr/bin/env bash
set -euo pipefail

TARGET_DIR="/var/log"
echo "=== Top 5 Storage Consumers in $TARGET_DIR ==="

sudo du -h --max-depth=1 "$TARGET_DIR" 2>/dev/null \
  | sort -hr \
  | head -n 6

# Illustrative output (reviewed against documentation)
=== Top 5 Storage Consumers in /var/log ===
4.2G	/var/log
2.8G	/var/log/journal
850M	/var/log/nginx
320M	/var/log/audit
110M	/var/log/apt

du generates human-readable disk sizes, and sort -hr orders them from largest to smallest, highlighting storage bottlenecks.

Web Server Analytics: Identifying Top 5 Remote Client IP Addresses

Parse an Nginx access log to aggregate and order the most active visitors by request volume.

#!/usr/bin/env bash
set -euo pipefail

LOG="/var/log/nginx/access.log"
echo "=== Top 5 Active Client IP Addresses ==="

awk '{print $1}' "$LOG" \
  | sort \
  | uniq -c \
  | sort -nr \
  | head -n 5 \
  | while read -r count ip; do
      printf "%6d requests from %s\n" "$count" "$ip"
    done

# Illustrative output (reviewed against documentation)
=== Top 5 Active Client IP Addresses ===
  1842 requests from 198.51.100.44
   940 requests from 203.0.113.12
   812 requests from 192.0.2.89
   310 requests from 198.51.100.12
   115 requests from 203.0.113.88

This classic pipeline uses sort to group identical IPs for uniq -c, followed by sort -nr to rank attackers or crawlers.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding sort inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

When sorting large files from untrusted sources, be mindful of temporary disk usage. By default, sort spills temporary merge runs into /tmp. If an attacker feeds an unconstrained multi-gigabyte dataset, /tmp may fill up, causing other system daemons to fail. Use -T to redirect temporary files to a dedicated scratch partition.

In shell scripts comparing cryptographic hashes or deterministic tokens, always enforce LC_ALL=C. Locale-dependent sorting can alter character ordering across different server environments, leading to subtle verification discrepancies.

GNU/Linux, BSD, and BusyBox Implementation Differences

The options -n, -r, -u, -k, and -t are strictly standardized in POSIX.1 and function identically across GNU, BSD, and BusyBox implementations.

The -h (--human-numeric-sort) and -V (--version-sort) options are GNU coreutils extensions. On BSD platforms (macOS, FreeBSD) or minimal BusyBox systems (Alpine Linux), sort -h and sort -V may be unsupported. For portable scripts, convert sizes to raw byte integers before sorting.

Troubleshooting Common Errors and Diagnostics

Numbers sorting out of order (e.g. 10 appears before 2)

Root Cause: sort was executed without the -n (--numeric-sort) flag, resulting in lexicographical ASCII comparison where '1' comes before '2'.

Resolution: Add the -n flag for numerical sorting.

sort -n numbers.txt

sort: /tmp/sortXXXXXX: No space left on device

Root Cause: The dataset being sorted exceeds available free space in the default /tmp filesystem partition during external merge sorting.

Resolution: Specify an alternate temporary directory with ample storage using -T.

sort -T /var/scratch/ -S 4G large_data.csv

Inconsistent sort ordering between local machine and server

Root Cause: The two systems have different locale configurations (e.g. en_US.UTF-8 vs C.UTF-8), altering collation weight rules for punctuation and capitalization.

Resolution: Prefix sort with LC_ALL=C to enforce standard byte-order collation.

LC_ALL=C sort file.txt

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
Use GNU sort's -o option: sort -o file.txt file.txt reads file.txt completely before overwriting it, avoiding the shell truncation bug.
sort -u deduplicates lines directly within the sorting engine, saving CPU and I/O cycles compared to spawning a secondary uniq process. However, uniq -c provides occurrence counts, which sort -u cannot do alone.
Specify multiple -k flags: sort -k1,1 -k2,2nr data.txt sorts first by column 1 alphabetically ascending, and then by column 2 numerically descending.
LC_ALL=C enforces raw byte ASCII comparison, bypassing expensive Unicode collation rules. This makes sorting up to 5 times faster and guarantees identical results across all Linux machines.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Cloud & DevOps•

How to Close File Descriptors Above 9 in Dash Shell

Attempting to close a file descriptor above 9 in Dash using exec 10<&- results in a 10: not found error because Dash's POSIX lexer only recognizes single-digit file descriptors (0–9) in redirection operators. This guide explains the exact parser limitation, why FDs 10+ are reserved for internal shell state, and how to safely close inherited file descriptors using close_range, Python, or Perl wrappers.

RR
Rajesh Rai
Read More
Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout