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
10For sizes such as 4K or 2G, GNU and BSD sort offer -h:
$ du -sh * | sort -hSort 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
bSave the result safely
This destroys the file, because the shell empties it before sort runs:
$ sort names.txt > names.txtUse -o, which is allowed to name the input file:
$ sort -o names.txt names.txtThe streams and text lab has data to practise on.
Try it
- Run
printf '5\n40\n3\n' | sortand then add-n. - Add
-rto list the largest number first. - Sort
/etc/passwdby user ID withsort -t: -k3,3n /etc/passwd. - 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.