Natural vs alphabetical vs plain sort
| Natural | Alphabetical | Plain (byte order) |
|---|---|---|
Apple.txt | Apple.txt |
Apple.txt |
banana.txt | banana.txt |
File1.txt |
File1.txt | File1.txt |
banana.txt |
file2.txt | file10.txt |
file10.txt |
file10.txt | file2.txt |
file2.txt |
image-9.png | image-10.png |
image-10.png |
image-10.png | image-9.png |
image-9.png |
“Plain” is what JavaScript’s .sort() without a compare function and LC_ALL=C sort give: uppercase
first, and digits compared one at a time.
Sorting lines in code
sort names.txt # alphabetical (locale rules)
sort -f names.txt # ignore case
sort -V files.txt # natural / version order: file2 before file10
sort -n counts.txt # numeric, by the leading number
sort -rn counts.txt # numeric, largest first
sort -u names.txt # sorted and unique
shuf names.txt # random order
const lines = text.split('\n');
// Natural, case-insensitive
const collator = new Intl.Collator('en', { numeric: true, sensitivity: 'base' });
lines.sort(collator.compare);
// By length, then alphabetically
lines.sort((a, b) => a.length - b.length || a.localeCompare(b));
import re
lines = text.splitlines()
sorted(lines, key=str.casefold) # alphabetical, ignoring case
def natural_key(s):
return [int(t) if t.isdigit() else t.casefold() for t in re.split(r"(\d+)", s)]
sorted(lines, key=natural_key) # file2 before file10
Only want each line once? Remove duplicate lines keeps the original order. To flip the order of lines without sorting, use reverse text.
Frequently asked questions
What is natural sort order?
Natural order compares runs of digits as numbers, so file2 comes before file10, the way a person would sort them and the way Finder and Windows Explorer show files. A plain alphabetical sort compares character by character, so file10 lands before file2 because “1” is less than “2”.
How does numeric sort work?
Each line is sorted by the number it starts with, including negative numbers, decimals and thousands separators (1,500). Lines that don’t start with a number are put after the numbers, in natural order. Use it for lists like “42 requests” or output from du and wc.
Is the shuffle really random?
Yes. It uses the Fisher–Yates algorithm with the browser’s cryptographically secure random number generator, so every order is equally likely. Shuffling with array.sort(() => Math.random() - 0.5), a common shortcut, is biased and should be avoided.
Why do uppercase letters come first in some sorts?
In ASCII and Unicode, all uppercase letters (A–Z) come before all lowercase ones (a–z), so a plain byte sort puts “Zebra” before “apple”. This tool sorts with locale rules and ignores case by default; untick “Ignore case” to put uppercase before lowercase when two lines are otherwise equal.