How do I recursively visit and delete all files in a particular folder which has spaces in sh?

StackOverflow https://stackoverflow.com/questions/22864687

  •  27-06-2023
  •  | 
  •  

Question

I am currently using

p=` ls -l -p $MYDIR | egrep '^d' | awk '{print $9}' 

for getting all the folders and then

for dirs in ${p}
do

for recursively opening the folders. It works fine for folder name without spaces, but for folder names with spaces, the second part of the folder name is selected as a seperate folder.

Was it helpful?

Solution

To iterate over all directories under $MYDIR,

 find "$MYDIR" -type d |
 while read dir; do
    printf '%s\n' "Deleting files in <$dir>"
    rm -f "$dir"/*
 done

Note that you must double quote the dir variable when using it to prevent the shell from performing word-splitting at spaces.

Skipping $MYDIR if you don't need it left as an exercise.

OTHER TIPS

You can use:-

find /opt/test  -type d ! -name "test" -exec echo rm -rf \"{}\" \; | sh

or

find -type d ! -name "." -exec echo rm -rf \"{}\" \; | sh
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top