How to Iterate Through Folders in Numerical Order

filesforwildcards

I have a bunch of folders which are labelled in this way:

 conf1
 conf2
 ...

But the order in the home directory is like

 conf1
 conf10
 conf100
 conf101
 ...
 conf2
 conf20
 conf200
 conf201
 ...

Because each folder contains a file named "distance.txt", I would like to be able to print the content of the distance.txt file, from each single folder, but in order, going from folder 1–>2–>3… to the final folder 272.

I tried several attempts, but every time the final file contains the all set of values in the wrong order; this is the piece of code I set:

   ls -v | for d in ./*/; 
     do (cd "$d" && cat distance.txt >> /path/to/folder/d.txt
         );
     done

As you can see I tried to "order" the folders with the command

ls -v

and then to couple the cycle to iteratively save each file.

Can you kindly help me?

Best Answer

For such a relatively small set of folders you could use a numerical loop

for n in {1..272}
do
    d="conf$n"
    test-d "$d" && cat "$d/distance.txt" >> /path/to/folder/d.txt
done
Related Question