3

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
  • it's not in posix sort but both GNU and FreeBSD's sort support the -V or --version-sort option, which is a "natural sort" of numbers embedded within text. – cas Sep 22 at 3:57
5
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.

  • I see that option in the man page now! It was not clear at all to me at first. – jsb Sep 21 at 21:08
2

Please try this:

output | awk '{print gensub("[^0-9]*","","g")  " " $0 }' | sort -n | awk '{$1=""; print $0}' | sed 's/^ //g'

This isn't the most elegant solution but it works.

1

The answer(one of them, I'm sure) is:

sort -t _ -k 2 -g [filename with names+numbers or piped from another command with | - both situations will work ]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.