Sort Output 1,10,11..2 in Linux – How to Guide

linuxsort

Sometimes I need to add more disk to a database; for that, I need to list the disks to see what disks already exist.

The problem is that the output is always sorted as 1,10,11,12…2,20,21…3 etc.

How can I sort this output the way I want it? A simple sort does not work; I've also tried using sort -t.. -k.. -n.

Example of what I need to sort:

[root@server1 ~]# oracleasm listdisks
DATA1
DATA10
DATA11
DATA12
DATA2
DATA3
DATA4
DATA5
DATA6
DATA7
DATA8
DATA9
FRA1
FRA10
FRA11
FRA2
FRA3
..
OCR1
OCR2
OCR3
....

How I'd like to see the output:

DATA1
DATA2
DATA3
DATA4
DATA5
DATA6
DATA7
DATA8
DATA9
DATA10
DATA11
DATA12
FRA1
FRA2
FRA3
..
..
FRA10
FRA11
..
OCR1
OCR2
OCR3
....

Best Answer

Your best bet is piping to GNU sort, with GNU sort's --version-sort option enabled

so that would be oracleasm listdisks | sort --version-sort

From the info page

--version-sort’
     Sort by version name and number.  It behaves like a standard sort,
     except that each sequence of decimal digits is treated numerically
     as an index/version number.  (*Note Details about version sort::.)

On your input it gives me

DATA1
DATA2
DATA3
DATA4
DATA5
DATA6
DATA7
DATA8
DATA9
DATA10
DATA11
DATA12
FRA1
FRA2
FRA3
FRA10
FRA11
OCR1
OCR2
OCR3
Related Question