HOWTO: Use the Sort Command.
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.
Related Stories
POSTED IN: How To
5 opinions for HOWTO: Use the Sort Command.
paul
Nov 27, 2005 at 4:36 am
More on sorting on certain fields here: http://gnuru.org/index.pl?node_id=844
Jon
Nov 27, 2005 at 9:08 am
Thanks, Paul!
AboutDigital.ru » HOWTO: Использование команды ‘sort’
Jan 2, 2006 at 10:06 am
[…] Оригинальный текст статьи на английском языке. […]
Jon
Jan 2, 2006 at 10:37 am
I hope that’s a good comment…
yellowhead poker room
Jan 12, 2008 at 9:23 pm
yellowhead poker room…
Hitlerism dueling Pascal:moderately …
Have an opinion? Leave a comment: