I have a bunch of folders say /test/ and /test1/ and these both contain folders /x/ and /x/ contains some random files which I don't want. I want to recursively go through all folders and go into /x/ and delete all the contents.

But I can't seem to figure out how to ONLY delete contents within /x/ folder.


I would use the find command and use the -exec option in the expression.

Test this first to make sure that it's finding the correct directories and you get no false positives. Change into the directory you're wanting to start from and then type:

find . -type d -iname x

That should do a case insensitive search for all directories named "x" from the current working directory and recurse down. If the output of that looks correct, you can delete files in those directories by issuing the following:

find . -type d -iname x -exec rm {}/* \+

This will delete only the files contained in the directories named "x". If you wish to delete the "x" directories as well, use the following:

find . -type d -iname x -exec rm -Rf {} \+
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.