sort
sort is like lining up kids by name or height. It reorders lines of text alphabetically or by number, from start to end or the other way around.
In this page:
Syntax
sort [-n] [-r] file_name
sort
sort orders lines of text, alphabetically by default, or numerically with -n, and in reverse with -r. -k sorts by a specific field instead of the whole line.
It's frequently the first step in a pipeline before deduplicating or summarizing data.
Note:
Always add
-n when sorting numbers as text sorts them lexically, putting "10" before "2".Example: sort
#!/bin/bash
printf "10\n2\n33\n4\n" | sort
echo "---"
printf "10\n2\n33\n4\n" | sort -n
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Sorting numbers as text, so
10comes before2; use-n. - Sorting by the wrong field, as in
sort -k2, which sorts from field 2 to the end of the line; use-k2,2to sort only by field 2. - Expecting the same order on every machine, since the locale changes how upper and lower case letters sort; use
LC_ALL=C sort.
🔒
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: