Unix: Sorting information that isn't quite numeric

Sorting data numerically and alphanumerically isn't generally much of a challenge on Unix systems, but sometimes .5 is smaller than .11.

By  

Some that I have found quite useful are.

-r reverse the order of the sort
-b ignore leading blanks (as far as the sort is concerned, it will not remove them)
-c check and report on whether the input is in sort order
-M sort in month order where months are Jan, Feb, etc.
-m merge files before sorting their joined content
-u remove duplicates

Here are some examples of commands using these options:

Sort dates in month order.

$ sort -M dates
Jan 4
Jan 8
Feb 2
Mar 18
Apr 26
May 1
Jun 26
Jul 26
Aug 6
Sep 10
Sep 14
Sep 23
Sep 25
Sep 4
Oct 19

Sort dates in reverse month order.

$ sort -M -r dates
Oct 19
Sep 4
Sep 25
Sep 23
Sep 14
Sep 10
Aug 6
Jul 26
Jun 26
May 1
Apr 26
Mar 18
Feb 2
Jan 8
Jan 4

Merge two files of dates and display in month order.

$ sort -m dates dates2 | sort -M
Jan 1
Jan 4
Jan 8
Feb 2
Mar 18
Mar 18
Apr 26
May 1
Jun 26
Jul 26
Aug 6
Sep 10
Sep 14
Sep 23
Sep 25
Sep 4
Oct 19
Nov 28
Dec 25

Do the same thing, but remove duplicate dates.

$ sort -m -u dates dates2 | sort -M
Jan 1
Jan 4
Jan 8
Feb 2
Mar 18
Apr 26
May 1
Jun 26
Jul 26
Aug 6
Sep 10
Sep 14
Sep 23
Sep 25
Sep 4
Oct 19
Nov 28
Dec 25

I have run into enough situations where sorting data by IP address has saved me a lot of time and effort that I have turned my sort-by-IP command into an alias that I can now use anytime I need it.

$ alias byIP='sort -n -t . -k 1,1 -k 2,2 -k 3,3 -k 4,4'
$ getNodes | byIP
10.1.12.98
10.2.99.21
10.3.7.11
10.3.45.7
10.3.45.67
192.168.0.1

Read more of Sandra Henry-Stocker's Unix as a Second Language blog and follow the latest IT news at ITworld, Twitter and Facebook.

Photo Credit: 

flickr /Key Foster

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Operating SystemsWhite Papers & Webcasts

See more White Papers | Webcasts

Ask a Question
randomness