b5media.com

Advertise with us

Enjoying this blog? Check out the rest of the Technology Channel Subscribe to this Feed

New Linux User

HOWTO: Use the Sort Command.

by Jon on November 25th, 2005

I’m not sure if this entry should have been a ‘Geeky Fun’ posting, or a HOWTO because you can do some interesting, but possibly useless stuff with the sort command.

The sort command will display a text file sorted in a specified order. From the man sort command:

Write sorted concatenation of all FILE(s) to standard output.

I like my definition better.

Consider if I have a text file containing the names of all the cars in my garage as follows:

  • Porsche
  • Audi
  • Ferrari
  • BMW
  • Lexus

Note that the file is no particular order. If I issue the command:

sort cars

The file will be displayed in my terminal window sorted alphabetically:

Audi
BMW
Ferrari
Lexus
Porsche

Sort can also be used to sort more than one file and merge them together. For example, consider if I have a text file named ’shopping’ with the following contents:

Zebras
Carrots
Apples
Mangoes

Now if I type:

sort cars shopping

The two files will be sorted together and the output will be:

Apples
Audi
BMW
Carrots
Ferrari
Lexus
Mangoes
Porsche
Zebras

As with most GNU/Linux commands, there are a variety of switches that can be applied to the end of the sort command that affect its output. Some of the options available through these switches allow you to output to a file rather than the screen, reverse the output, consider month ordering (as in Jan is greater than Dec), only sort on alphanumeric characters, and many more.

I have used the sort command now and again, but I learned something very neat about it that I didn’t know from The Linux Documentation Project. The sort command can be used to create a text file that is sorted in real time. For example, typing:

sort > cars

Puts me into data entry mode. I can now type the name of each of my cars followed by the enter key to enter them into the cars text file. When I’m done, hitting Ctrl-D will put me back to my command prompt. Take a look at the cars text file - it will have the names of the cars I typed already sorted in alphabetical order.

Pretty neat.

POSTED IN: How To

5 opinions for HOWTO: Use the Sort Command.

Have an opinion? Leave a comment:




Check Spelling
Activate Spell Check while Typing
Site Meter
Close
E-mail It