I have found the command to delete files older than 5 days in a folder
find /path/to/files* -mtime +5 -exec rm {} \;
But how do I also do this for subdirectories in that folder?
|
I have found the command to delete files older than 5 days in a folder
But how do I also do this for subdirectories in that folder? |
||||
|
Be careful with special file names (spaces, quotes) when piping to rm. There is a safe alternative - the -delete option:
That's it, no separate rm call and you don't need to worry about file names. Replace |
|||||||||||||||||
|
|
Note that this command will not work when it finds too many files. It will yield an error like:
Meaning the exec system call's limit on the length of a command line was exceeded. Instead of executing rm that way it's a lot more efficient to use xargs. Here's an example that works:
This will remove all files (type f) modified longer than 14 days ago under /root/Maildir/ recursively from there and deeper (mindepth 1). See the find manual for more options. |
|||||||||
|
|
It's the same. You just have to provide the parent directory rather than the prefix of files. In your example, it would be:
This will delete all the files older than 5 days which are under To delete empty sub-directories, refer to @Costas comment above. |
|||||||||
|
find /path/to -type d -empty -delete– Costas Apr 7 '15 at 16:39rm test one. (Which will delete a file called "test" and a file called "one", but not a file called "test one"). Hint: -delete or -print0 – Hennes Apr 7 '15 at 17:17findto avoid issues with special characters, as mentioned in the answer's first line. E.g.:find /path/to/files/ -exec somecommand '{}' \;– Walf Jun 17 '16 at 1:54