Home > Software engineering >  Iterate a function through every subfolder
Iterate a function through every subfolder

Time:10-14

I have a function that takes a file, does some operation, and creates a bunch of output files. I have 100 subfolders named:

d066, d067, d068.... d165, d166

Each of them has only 1 file. What I want to do is go into each subfolder, grab the name of the file, apply the function to it, leave the subfolder, enter the next one and so on.

I wrote this script:

for i in {60..166}; do
    
    if [ $i -lt 100 ];
    then 
        var2=d0$i
    else
        var2=d$i
    fi             
    cd $var2 || exit             
    f=$(find . -type f)   
    gd2e.py -rnxFile $f   
    cd ..                
    
done

The issue is that my code gets out of the folder containing the subfolder, and stops. Does anyone knows of a better way to do this ?

CodePudding user response:

Assuming the function can work with a directoy as part of the input parameter (eg, gd2e.py -rnxFile ${i}/${f}), a few ideas to streamline the current code:

while read -r f
do
    gd2e.py -rnxfFile "${f}"
done < <(find d{060..166} -type f)

If the d{060..166} directories can have subdirectories that you don't want to scan we can add a -maxdepth 1 to the find:

while read -r f
do
    gd2e.py -rnxfFile "${f}"
done < <(find d{060..166} -maxdepth 1 -type f)
  • Related