m47h
m47h

Reputation: 1703

Sort filenames without leading zeros

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?

Upvotes: 20

Views: 7221

Answers (2)

Sparhawk
Sparhawk

Reputation: 1677

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.

Upvotes: 2

fedorqui
fedorqui

Reputation: 289545

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).

Upvotes: 39

Related Questions