Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort file names by version numbers?

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?

like image 257
sid_com Avatar asked Oct 28 '10 08:10

sid_com


People also ask

How do you sort names in a file?

To sort files in a different order, click the view options button in the toolbar and choose By Name, By Size, By Type, By Modification Date, or By Access Date. As an example, if you select By Name, the files will be sorted by their names, in alphabetical order. See Ways of sorting files for other options.

How do you sort file?

Sort Files and FoldersIn the desktop, click or tap the File Explorer button on the taskbar. Open the folder that contains the files you want to group. Click or tap the Sort by button on the View tab. Select a sort by option on the menu.

How do you sort file names in Linux?

If you add the -X option, ls will sort files by name within each extension category. For example, it will list files without extensions first (in alphanumeric order) followed by files with extensions like . 1, . bz2, .


2 Answers

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.

like image 66
Dennis Williamson Avatar answered Oct 15 '22 18:10

Dennis Williamson


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.

like image 26
Benoit Avatar answered Oct 15 '22 16:10

Benoit