How can I sort file names by version numbers?

£可爱£侵袭症+ 提交于 2019-11-26 22:58:10

问题


In the directory "data" are these files:

command-1.9a-setup
command-2.0a-setup
command-2.0c-setup
command-2.0-setup

I would like to sort the files to get this result:

command-1.9a-setup
command-2.0-setup
command-2.0a-setup
command-2.0c-setup

I tried this

find /data/ -name 'command-*-setup' | sort --version-sort --field-separator=- -k2 

but the output was

command-1.9a-setup
command-2.0a-setup
command-2.0c-setup
command-2.0-setup

The only way I found that gave me my desired output was

tree -v /data

How could I get with sort the output in the wanted order?


回答1:


Edit: It turns out that Benoit was sort of on the right track and Roland tipped the balance

You simply need to tell sort to consider only field 2 (add ",2"):

find ... | sort --version-sort --field-separator=- --key=2,2

Original Answer: ignore

If none of your filenames contain spaces between the hyphens, you can try this:

find ... | sed 's/.*-\([^-]*\)-.*/\1 \0/;s/[^0-9] /.&/' | sort --version-sort --field-separator=- --key=2 | sed 's/[^ ]* //'

The first sed command makes the lines look like this (I added "10" to show that the sort is numeric):

1.9.a command-1.9a-setup
2.0.c command-2.0c-setup
2.0.a command-2.0a-setup
2.0 command-2.0-setup
10 command-10-setup

The extra dot makes the letter suffixed version number sort after the version number without the suffix. The second sed command removes the prefixed version number from each line.

There are lots of ways this can fail.




回答2:


If you specify to sort that you only want to consider the second field (-k2) don't complain that it does not consider the third one.

In your case, run sort --version-sort without any other argument, maybe this will suit better.




回答3:


Looks like this works:

find /data/ -name 'command-*-setup' | sort -t - -V -k 2,2

not with sort but it works:

tree -ivL 1 /data/ | perl -nlE 'say if /\Acommand-[0-9][0-9a-z.]*-setup\z/'

-v: sort the output by version
-i: makes tree not print the indentation lines
-L level: max display depth of the directory tree




回答4:


Old post, but... ls -l --sort=version may be of assistance (although for OP's example the sort is the same as done by ls -l in a RHEL 7.2):

command-1.9a-setup
command-2.0a-setup
command-2.0c-setup
command-2.0-setup

YMMV i guess.




回答5:


$ cat files
command-1.9a-setup
command-2.0c-setup
command-10.1-setup
command-2.0a-setup
command-2.0-setup

$ cat files | sort -t- -k2,2 -n
command-1.9a-setup
command-2.0-setup
command-2.0a-setup
command-2.0c-setup
command-10.1-setup

$ tac files | sort -t- -k2,2 -n
command-1.9a-setup
command-2.0-setup
command-2.0a-setup
command-2.0c-setup
command-10.1-setup


来源:https://stackoverflow.com/questions/4041210/how-can-i-sort-file-names-by-version-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!