Unix Commands  «Prev  Next»
Lesson 4 The sort command
Objective Use the sort command to sort by column.

Unix Sort Command

Use the sort command to sort the contents of a text file. The clothes file, listed below, contains an inventory of the clothes in my closet. Each line contains the color, description, and number for a particular type of clothing.

      
Black,coat,4
Blue,pair of shoes,5
Black,shirt,2
Green,shirt,3
Red,coat,1
Green,coat,1
Black,trousers,3                

The file makes a great candidate for use with the sort command because it is a text file with a separate piece of information on each line. Each line contains three itemsseparated by commas. These items are interpreted as columns of information. The locations of the columns are identified with a number, starting with +0 for the first column (color), +1 for the second column (description), and +2 for the third column (quantity).
If I wanted to sort my clothes file by column, I would use the following command:
$ sort –t, +1 clothes

When forming a sort command, you should include the –t option which specifies the character used to separate columns in the file. The –t option must be followed by a separation character, such as the comma used in the above command. You must also indicate the column number and file name you want the sort command to act upon.

Sort does not modify your file

Just using the sort command does not permanently change the file you are sorting. It only shows what the file would look like if it were sorted using various options. If you want to change your file, use the –o option with the sort command. The following command changes the contents of the clothes file so that it is sorted by color, column +0.
$ sort –t, +0 –o clothes clothes

Using the –o option tells the sort command to store your output in a file, in this case clothes. This file can have the same name as your original file, which results in a new version of the original. If you use a different file name, then your new file will contain the sorted information and your original file will contain the unsorted information.