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.txtNumbers in reverse
sort -r flips the order. The largest number comes first.
$ cd ~/practice
$ sort -r data/numbers.txtNames in order
sort works on words too. The names come out in letter order.
$ cd ~/practice
$ sort data/names.txtExample
$ cd ~/practice
$ sort -u data/names.txt
$ sort -n data/numbers.txtKey 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?