Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ordering in bash "for" loop

Tags:

bash

unix

sorting

Is there any way to control the sorting that occurs when I run a, for i in * ; do; echo $i; done; in my directory. It seems to always use ascii sorting. Anyway to do a numeric sort?

Thanks, Vivek

like image 990
user393144 Avatar asked Oct 20 '11 19:10

user393144


2 Answers

How about making your filenames so they sort naturally as numbers, i.e. padded with leading zeros. Instead of 1 .. 10 .. 100, use 001 ..010 .. 100?

To include sub-directories:

for i in $( ls -d * | sort -n ); do echo $i; done;

To exclude sub-directories:

for i in $( ls | sort -n ); do echo $i; done;

I hope this helps.

like image 198
shellter Avatar answered Oct 26 '22 01:10

shellter


You can always use sort(1) and its numeric sort:

for i in $(ls -1 * | sort -n) ; do echo $i ; done
like image 6
bos Avatar answered Oct 26 '22 02:10

bos