Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Portable way to achieve ls' -v flag (i.e. sort by version)?

Tags:

I'm working on a some build scripts that I'd like to depend on only standardized features. I need to sort some files by version. Say the files are bar-1.{0,2,3} bar-11.{0,2,3}.

By default, ls gives me:

bar-1_0
bar-11_0
bar-11_2
bar-11_3
bar-1_2
bar-1_3

Getting what I want is easy using 'ls -v':

bar-1_0
bar-1_2
bar-1_3
bar-11_0
bar-11_2
bar-11_3

The problem is that 'ls -v' is not standard. Standard sort also seems to lack the option I want, though I could be looking at old versions of the specs.

Can anyone suggest a portable way to achieve this effect short of writing my own sort routine?

Thanks, Rhys

like image 569
Rhys Ulerich Avatar asked Sep 26 '09 18:09

Rhys Ulerich


People also ask

How do I sort ls by file size?

To sort files by size, use the option -S with the ls command. Mind it, it's capital S for sorting. That's good but you can make it better by adding the -h option. This option makes the output of the ls command displays the file size in human readable formats.

How use Mtime command in Linux?

Modified timestamp (mtime) indicates the last time the contents of a file were modified. For example, if new contents were added, deleted, or replaced in a file, the modified timestamp is changed. To view the modified timestamp, we can simple use the ls command with -l option.


1 Answers

sort -n -t- -k2 seems to do what you want. -n gives you numeric (i.e. not alphabetic) sort; -t- sets the field separator to -, and -k2 selects the second field, i.e. the version number.

My sort, on Ubuntu, even does the part with the underscore correctly, but I'm not sure if that is standard. To be sure, you could sort by the minor version first, then by major version.

like image 86
Thomas Avatar answered Oct 02 '22 11:10

Thomas