Ubuntu – Delete files older than 5 days as well as in all subfolders

deletedirectoryrm

I need to delete all files older than 5 days in all subfolders, but not the folders themselves. I know the command:

find /path/to/files* -mtime +5 -exec rm {} \;

But how can I tell Ubuntu to check in all subfolders, yet never delete the folders themselves. Will I need a -maxdepth 5 somewhere?

Thanks.

Best Answer

First of all, don't give a glob to find (no files*), just give it the parent directory (/path/to/). It will deal with recursing into it and finding all files. Next, rm will never delete directories, so you don't need to worry about that either. Still, the simplest way is:

find /path/to/ -type f -mtime +5 -delete

Note the -type f which tells find to only look at files and the -delete which, well, deletes them. This is more efficient than calling a separate rm for each result.