Using sorting keys — an example
By default, sort sorts according to all the information in the record, in the order given in the record. Since the name of the comic book is the first thing on the line, the output is sorted according to comic book name. But suppose that you want to sort according to some different piece of information. For example, suppose you want to sort by date of publication. You can do this by specifying sorting keys.
A sorting key tells sort to look at specific fields in a record, instead of looking at each record as a whole. A sorting key also tells what kind of information is stored in a particular field (for example, an ordinary word, a number, or a month) and how that information should be sorted (in ascending or descending order).
A sorting key can refer to one or more fields. Fields are specified by number. The first field in a record is field number 1, the field after the first separator character is field number 2, and so on. In the comic book list, the month is field number 3, and the year is field number 4.
-k start_field[.char1] [opts] [,end_field[.char2] [opts]]
where start_field, end_field, char1, and char2 are
all integers.
- start_field indicates which field in the input record contains the start of the sorting key.
- char1 indicates which character in that field is the first character of the key. Omitting char1 means the key begins with the first character of the starting field.
- d
- Indicates that the field contains uppercase, lowercase, or mixed-case letters, letters and digits, or digits. sort sorts the field in dictionary order, ignoring all other characters.
- M
- Indicates that the field contains the name of a month. sort looks only at the first three characters of the name, so January, JAN, and jan are all equal.
- n
- Indicates that the field contains an integer (positive or negative).
Putting an r after any of these letters tells sort to sort in reverse order (from highest to lowest rather than lowest to highest). For example, Mr means to sort in the order December, November, October, and so on.
-k 4n
-k 3M
sort -t: -k4n -k3M comics.lst >sorted.lst
The
file to be sorted comes after the various options. This is the order
that you must use. The redirection construct can come anywhere on
the line, but is usually put at the end.