1. Computing

Discuss in my forum

Example uses of the command "sort"

A Brief Introduction

By

In order to sort the lines in a file you would use a command line like:

$ sort -k2 test.txt
which sorts the file "test.txt" according to the characters starting at the second column (k2 refers to the second column). Assuming the input file contents is:

1, Justin Timberlake, Title 545, Price $7.30
2, Taylor Swift, Title 723, Price $7.90
3, Mick Jagger, Title 610, Price $7.90
4, Lady Gaga, Title 118, Price $7.30
5, Johnny Cash, Title 482, Price $6.50
6, Elvis Presley, Title 335, Price $7.30
7, John Lennon, Title 271, Price $7.90
8, Michael Jackson, Title 373, Price $5.50
The sorted output would look like this:

6, Elvis Presley, Title 335, Price $6.30
7, John Lennon, Title 271, Price $7.90
5, Johnny Cash, Title 482, Price $6.50
1, Justin Timberlake, Title 545, Price $6.30
4, Lady Gaga, Title 118, Price $6.30
8, Michael Jackson, Title 373, Price $5.50
3, Mick Jagger, Title 610, Price $7.90
2, Taylor Swift, Title 723, Price $7.90
If you sorted the file with -k4 (using the line contents starting at column 4), the output would be:

$ sort -k4 test.txt
4, Lady Gaga, Title 118, Price $6.30
7, John Lennon, Title 271, Price $7.90
6, Elvis Presley, Title 335, Price $6.30
8, Michael Jackson, Title 373, Price $5.50
5, Johnny Cash, Title 482, Price $6.50
1, Justin Timberlake, Title 545, Price $6.30
3, Mick Jagger, Title 610, Price $7.90
2, Taylor Swift, Title 723, Price $7.90
And

$ sort -k7 test.txt
Would produce

8, Michael Jackson, Title 373, Price $5.50
1, Justin Timberlake, Title 545, Price $6.30
4, Lady Gaga, Title 118, Price $6.30
6, Elvis Presley, Title 335, Price $6.30
5, Johnny Cash, Title 482, Price $6.50
2, Taylor Swift, Title 723, Price $7.90
3, Mick Jagger, Title 610, Price $7.90
7, John Lennon, Title 271, Price $7.90
The -r option will reverse the sorting. For example,

$ sort -k7 -r test.txt
Yields

7, John Lennon, Title 271, Price $7.90
3, Mick Jagger, Title 610, Price $7.90
2, Taylor Swift, Title 723, Price $7.90
5, Johnny Cash, Title 482, Price $6.50
6, Elvis Presley, Title 335, Price $6.30
4, Lady Gaga, Title 118, Price $6.30
1, Justin Timberlake, Title 545, Price $6.30
8, Michael Jackson, Title 373, Price $5.50
In order to save the sorted list in a file you could use the "redirect" operator:

sort -k7 -r test.txt > test_new.txt
where "test_new.txt" would be the new file. Of course you can also apply the sort command to the output of a stream, such as the "pipe" operator:

$ ls -al | sort -r -n -k5
This sorts the output of the file listing generated by ls by file size, starting with largest files. The -n operator specifies "numeric" sorting as compared to alphabetic.

For more command options see the sort man page.

  1. About.com
  2. Computing
  3. Linux
  4. Linux / Shell Commands
  5. Example uses of the Linux Command "sort"

©2014 About.com. All rights reserved.