Linux – How to recursively remove subdirectories and files, but not the first parent directory

command linelinuxmacosterminal

I'm able to use the following to remove the target directory and recursively all of its subdirectories and contents.

find '/target/directory/' -type d -name '*' -print0 | xargs -0 rm -rf

However, I do not want the target directory to be removed. How can I remove just the files in the target, the subdirectories, and their contents?

Best Answer

The previous answer is almost correct. However, you shouldn't quote the shell glob characters if you want them to work. So, this is the command you're looking for:

rm -rf "/target/directory with spaces/"*

Note that the * is outside of the double quotes. This form would also work:

rm -rf /target/directory\ with\ spaces/*

If you have the * in quotes as shown above, then it will only attempt to remove the single file literally named * inside the target directory.