comp.org.uk

Networking | Programming | Security | Linux | Computer Science | About

Sorting using the sort command

Sometimes you’ll create an output file that you want sorted. To do so, you can use a command that’s called, appropriately enough, sort. This command can sort in several ways, including the following:

Ignore Case

Ordinarily, sort sorts by ASCII value, which differentiates between uppercase and lowercase letters. The -f or --ignore-case option causes sort to ignore case.

Month Sort

The -M or --month-sort option causes the program to sort by three-letter month abbreviation (JAN through DEC).

Numeric Sort

You can sort by number by using the -n or --numeric-sort option.

Reverse Sort Order

The -r or --reverse option sorts in reverse order.

Sort Field

By default, sort uses the first field as its sort field. You can specify another field with the -k field or --key=field option. (The field can be two numbered fields separated by commas, to sort on multiple fields.)

As an example, suppose you wanted to sort the following file (names.txt) by first name.

555-2397 Beckett, Barry
555-5116 Carter, Gertrude
555-7929 Jones, Theresa
555-9871 Orwell, Samuel

You could do so like this:

$ sort -k 3 names.txt

and the output would be:

555-2397 Beckett, Barry
555-5116 Carter, Gertrude
555-9871 Orwell, Samuel
555-7929 Jones, Theresa

The sort command supports a large number of additional options, many of them quite exotic. Consult sort’s man page for details.


Published on Wed 04 July 2001 by Lai Yahui in Linux with tag(s): sort