The sort Command

team bbl


If you want to sort the contents of a plain text file, you can bring it into your word processor and sort it. However, Linux has a sort command that is much faster and often easier to use. The command to sort a file named unsorted.txt is:

 sort unsorted.txt 

The unsorted and the sorted contents of the file are below:

Unsorted

Sorted

Little Boy Blue

Jack Horner

Jack Horner

Little Bo Peep

Little Bo Peep

Little Boy Blue


This is the simplest form of sort, which is sufficient for many needs. In addition, the sort command has several options which affect the sorting procedure. Table 7-5 shows the most useful options.

Table 7-5. Options for the sort Command

Option

What it does

-ofilename

Save the output in the specified file.

-r

Sort in reverse order.

-u

Remove identical lines.

-k

Specify which key to sort on.

-t

Define a character to separate the keys in the text line.


More complicated sorts are possible using the-k and -t options. These options allow you to specify exactly which text in the line to sort on, rather than just sorting from the beginning of the line. For instance, you could use the following command:

 sort k2 t" " unsorted.txt 

The -t defines an empty space to be the character that separates the keys. The -k2 specifies key 2 as the key to sort on. Thus, sort will sort the lines based on the second word in the line: The output for this sort is:

 Little Bo Peep Little Boy Blue Jack Horner 

    team bbl



    Spring Into Linux
    Spring Into Linux
    ISBN: 0131853546
    EAN: 2147483647
    Year: 2005
    Pages: 362
    Authors: Janet Valade

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net