Skip to content

Linux Foundations / Find your way around Linux ยท Step 42 of 63

Lesson: sortSwitch
โ† Linux Foundations

Shell and files

sort

Learn to order lines alphabetically, numerically or by a chosen field with sort.

sort reads lines and prints them in order. It does not change the input file.

Basic sorting

$ cat fruit.txt
cherry
apple
banana
$ sort fruit.txt
apple
banana
cherry

-r reverses the order. Text order follows your locale, so upper and lower case may mix differently on two systems. LC_ALL=C sort gives plain byte order, where capitals come before lowercase letters.

Numbers need -n

Compared as text, 10 comes before 9 because 1 comes before 9.

$ printf '9\n10\n2\n' | sort
10
2
9
$ printf '9\n10\n2\n' | sort -n
2
9
10

For sizes such as 4K or 2G, GNU and BSD sort offer -h:

$ du -sh * | sort -h

Sort by a field

-k chooses the key and -t sets the field separator.

$ cat scores.txt
maya:82
omar:95
li:78
$ sort -t ':' -k 2,2 -n scores.txt
li:78
maya:82
omar:95

-k 2,2 means the key starts and ends at field 2. Plain -k 2 would run from field 2 to the end of the line.

Remove duplicates

-u prints only one of each set of equal lines.

$ printf 'b\na\nb\n' | sort -u
a
b

Save the result safely

This destroys the file, because the shell empties it before sort runs:

$ sort names.txt > names.txt

Use -o, which is allowed to name the input file:

$ sort -o names.txt names.txt

The streams and text lab has data to practise on.

Try it

  1. Run printf '5\n40\n3\n' | sort and then add -n.
  2. Add -r to list the largest number first.
  3. Sort /etc/passwd by user ID with sort -t: -k3,3n /etc/passwd.
  4. Create a file and sort it in place with -o.

Check your understanding

sort

All 5 sections ยท no timer

Unlimited retries

Questions from every section are combined into one assessment. Answer them all correctly to complete the article.

Your completion saves in this browser. Sign in to sync it to your account.