Linux – How to delete files within a directory and subdirectories but not the folders

command linelinuxUbuntu

How do I delete files within a directory and subdirectories but not the folders?

I need to be able to do this on the Linux command line.

With rm?

Best Answer

Traditional find

Use find. It will find all files (i.e. not directories) in the current folder. If you want to make sure you don't delete the wrong stuff, call this first.

find . -type f

Then, you can use the exec option to do something with these files – in this case rming them.

find . -type f -exec rm {} \;

find piped into xargs

You can also use the find output to feed into xargs, which will take the file paths as arguments for a rm command.

find . -type f -print0 | xargs -0 rm

The -print0 option is necessary to avoid breaking things with filenames containing whitespace. Generally, don't use such a thing without this option, it's highly insecure.

GNU find

GNU find also has a delete option. This is way more efficient than the exec way, as it doesn't have to fork a new process with rm. It is also more secure when considering file paths.

find . -type f -delete

The GNU manual for find has a very extensive section on deleting files.