Sorting on several fields

You can sort a file on several fields with the same sort command. The file is sorted on the first field; if some lines have the same value for this field they are sorted on the next field you specify and so on.

This is the file scores each line of which gives the initial, surname, gender, age and test score of a person. Each field is separated by a space.

   J. Arnott F 43 78
   T. Rice M 42 67
   M. Macdonald F 39 85
   A. Board M 36 43
   M. Mouzin F 27 57
   R. Bramley M 42 75

To sort the file on two fields, first by age (field 4) and then by score (field 5), placing the output in the file results.

   sort -o results +3 -5 scores

This gives the following result in the file results.

   M. Mouzin F 27 57
   A. Board M 36 43
   M. Macdonald F 39 85
   T. Rice M 42 67
   R. Bramley M 42 75
   J. Arnott F 43 78

From the first sort on field 4 (age) sort finds that Rice and Bramley are the same age so it now sorts these two lines on field 5 (score), placing Rice (67) before Bramley (75).


[Home] [Search] [Index] This site maintained by umk@astroa.physics.metu.edu.tr