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
?
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.Then, you can use the
exec
option to do something with these files – in this caserm
ing them.find
piped intoxargs
You can also use the
find
output to feed intoxargs
, which will take the file paths as arguments for arm
command.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 adelete
option. This is way more efficient than theexec
way, as it doesn't have to fork a new process withrm
. It is also more secure when considering file paths.The GNU manual for find has a very extensive section on deleting files.