Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort filenames without leading zeros

Tags:

bash

sorting

i would like to sort stereo imagefiles with the following pattern

img_i_j.ppm,

where i is the image counter and j is the id of the camera [0,1]. Currently, if i sort them using

ls -1 *.ppm | sort -n

the result looks like that:

img_0_0.ppm
img_0_1.ppm
img_10_0.ppm
img_10_1.ppm
img_1_0.ppm  
img_11_0.ppm                        
img_11_1.ppm                        
img_1_1.ppm  
img_12_0.ppm

But i need to have this output:

img_0_0.ppm
img_0_1.ppm
img_1_0.ppm
img_1_1.ppm
img_2_0.ppm  
img_2_1.ppm
...                        
img_10_0.ppm                        
img_10_1.ppm  
...    

Is this achievable without adapting the filename?

like image 293
m47h Avatar asked Sep 11 '13 14:09

m47h


People also ask

How do I sort file names?

Icon view. 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.


2 Answers

As seen on the comments, use

sort -V

I initially posted it as a comment because this parameter is not always in the sort binary, so you have to use sort -k -n ... (for example like here).

like image 129
fedorqui 'SO stop harming' Avatar answered Sep 18 '22 06:09

fedorqui 'SO stop harming'


ls (now?) has the -v option, which does what you want. From man ls:

-v     natural sort of (version) numbers within text

This is simpler than piping to sort, and follows advice not to parse ls.

If you actually intend to parse the output, I imagine that you can mess with LC_COLLATE in bash. Alternatively, in zsh, you can just use the glob *(n) instead.

like image 28
Sparhawk Avatar answered Sep 19 '22 06:09

Sparhawk