Sort – Sort by Contiguous Digits as a Single Number

awksedsort

A command outputs this:

file_0
file_1
file_10
file_11
file_12
file_13
file_14
file_15
file_2
file_3
file_4
file_5
file_6
file_7
file_8
file_9

How can I use awk or some other posix tool to actually sort it by the contiguous digits as a single number:

file_0
file_1
file_2
file_3
file_4
file_5
file_6
file_7
file_8
file_9
file_10
file_11
file_12
file_13
file_14
file_15

In general it should also work in case the digits is inside the file name, e.g.:

file_0.txt
file_1.txt
file_10.txt
file_11.txt
file_12.txt
file_13.txt
file_14.txt
file_15.txt
file_2.txt
file_3.txt
file_4.txt
file_5.txt
file_6.txt
file_7.txt
file_8.txt
file_9.txt

Best Answer

sort -nt '_' -k2 

Output:

file_0
file_1
file_2
file_3
file_4
file_5
file_6
file_7
file_8
file_9
file_10
file_11
file_12
file_13
file_14
file_15

or:

file_0.txt
file_1.txt
file_2.txt
file_3.txt
file_4.txt
file_5.txt
file_6.txt
file_7.txt
file_8.txt
file_9.txt
file_10.txt
file_11.txt
file_12.txt
file_13.txt
file_14.txt
file_15.txt

Tested with FreeBSD and GNU coreutils implementations of sort but would not work with busybox implementation. All options used are specified by POSIX.

Related Question