Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop over files in natural order in Bash?

I am looping over all the files in a directory with the following command:

for i in *.fas; do some_code; done; 

However, I get them in this order

vvchr1.fas   vvchr10.fas   vvchr11.fas vvchr2.fas ... 

instead of

vvchr1.fas vvchr2.fas vvchr3.fas ... 

what is natural order.

I have tried sort command, but to no avail.

like image 591
Perlnika Avatar asked Nov 03 '11 09:11

Perlnika


People also ask

How can I iterate over files in a given directory bash?

The syntax to loop through each file individually in a loop is: create a variable (f for file, for example). Then define the data set you want the variable to cycle through. In this case, cycle through all files in the current directory using the * wildcard character (the * wildcard matches everything).


1 Answers

readarray -d '' entries < <(printf '%s\0' *.fas | sort -zV) for entry in "${entries[@]}"; do   # do something with $entry done 

where printf '%s\0' *.fas yields a NUL separated list of directory entries with the extension .fas, and sort -zV sorts them in natural order.

Note that you need GNU sort installed in order for this to work.

like image 127
catalin.costache Avatar answered Sep 23 '22 15:09

catalin.costache