🎓 A1Learner
🔍
0 of 50 lessons completed

Sorting Lines

sort puts lines in order. The lines come out sorted, from first to last.

Numbers in order

sort prints the numbers from smallest to largest.

$ cd ~/practice
$ sort data/numbers.txt

Numbers in reverse

sort -r flips the order. The largest number comes first.

$ cd ~/practice
$ sort -r data/numbers.txt

Names in order

sort works on words too. The names come out in letter order.

$ cd ~/practice
$ sort data/names.txt

Example

$ cd ~/practice
$ sort -u data/names.txt
$ sort -n data/numbers.txt

Key points

  • Use sort to print the lines of a file in order.
  • Use sort -r to flip the order, from last to first.
  • Use sort -n to sort by number value.
  • Use sort -u to drop lines that repeat.
  • Sorting puts the same lines side by side.
  • sort never changes the file. It only prints the lines in order.

In this example, sort -u prints each name once. sort -n prints the numbers by value. The names lose their repeats, and the numbers keep their order.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which option sorts numbers by value?