7

Here's a subset of the file names in my file:

profile_10_1_1
profile_10_1_2
profile_1_1_1

I'm trying to sort them numerically in ascending order, that is starting from 1 onwards. I used the following command

sort -n filename

and also tried this:

sort -nk filename

But the ones with 10 will always be at the top of the list.

How do I write a command to get this desired output:

profile_1_1_1
profile_1_1_2
....
profile_9_1_1
....
profile_10_1_1
8
  • possible duplicate of List files sorted numerically Commented May 18, 2015 at 17:14
  • @CedianO that question applies to single numbers, these are more like version numbers.
    – Anthon
    Commented May 18, 2015 at 18:03
  • Yes indeed, but it works also here Commented May 18, 2015 at 18:04
  • See the last reply Commented May 18, 2015 at 18:05
  • See the reply of Volker Siegel Commented May 18, 2015 at 18:06

2 Answers 2

7

FreeBSD and GNU sort have a -V option for that.

sort -V < filename

GNU ls has a -v option. So if those files do exist, you could do:

xargs -d '\n' < filename ls -dv --

zsh has parameter expansion flags to sort arrays numerically:

printf '%s\n' ${(fno)"$(<filename)"}

Otherwise, portably, you'd have to do it like:

sort -t_ -k1,1 -k2,2n -k3,3n -k4,4n -k5,5n filename
0
3

-V does exactly what you want.

-V, --version-sort
              natural sort of (version) numbers within text

Works at least in GNU sort.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .