← Back to Bash Course | Chapter 11: Process Management | Lesson 7 of 12

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:

  1. sort
Syntax
bash
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

bash
#!/bin/bash
printf "10\n2\n33\n4\n" | sort
echo "---"
printf "10\n2\n33\n4\n" | sort -n
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
  1. Sorting numbers as text, so 10 comes before 2; use -n.
  2. Sorting by the wrong field, as in sort -k2, which sorts from field 2 to the end of the line; use -k2,2 to sort only by field 2.
  3. Expecting the same order on every machine, since the locale changes how upper and lower case letters sort; use LC_ALL=C sort.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.