Loop to execute a command in each subfolder

Issue

*Each folder has another folder from which I need to move all it’s contents one folder up and then delete it:

Main_folder
   -->DePreter.Jonas
       -->Huistaak1-HelloWorld_Jonas.DePreter.s.ua_poging_2019-11-12
          --> (Files and folders name doesn't matter)
   -->(another_name)
       -->Huistaa1-HelloWorld_(name)...
          --> more files
    ...

So what I need is to access each name folder (such as "DePreter.Jonas") and move all the files from Huistaak1-HelloWorld… to the name folder where it’s in and then delete the Huistaak1… folder

I have written this but this is way too long and I would like it in a loop.

cd DePreter.Jonas
mv */* */.* . 
find . -type d -name "Huistaak1*" -delete
cd ..

cd Feremans.Len
mv */* */.* . 
find . -type d -name "Huistaak1*" -delete
cd ..

cd Hofkens.Peter
mv */* */.* . 
find . -type d -name "Huistaak1*" -delete
cd ..

cd Janssens.Jan
mv */* */.* . 
find . -type d -name "Huistaak1*" -delete
cd ..

cd Peters.Jolien
mv */* */.* . 
find . -type d -name "Huistaak1*" -delete
cd ..

cd VanHoof.Sarah
mv */* */.* . 
find . -type d -name "Huistaak1*" -delete
cd ..

Solution

This might be what you are after:

cd /path/to/Main_folder || exit

for dir in */*/
do
    cd "$dir" || exit
    mv ./* ..
    cd - >/dev/null || exit
    rmdir "$dir"
done

Or, a more concise one without cding inside the loop body:

cd /path/to/Main_folder || exit

for dir in */*/
do
    mv "$dir"* "${dir%%/*}"
    rmdir "$dir"
done

Answered By – M. Nejat Aydin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published