What is the command to remove all files but not directories?
Olivia Zamora
Let's say I have a directory tree like this:
FOLDER: file1 file2 file3 Subfolder1: file1 file2 Subfolder2: file1 file2If I used rm -r FOLDER/*, everything in FOLDER would be deleted including sub-directories. How can I delete all files in FOLDER and in its sub-directories without deleting actual directories?
3 Answers
What you're trying to do is recursive deletion. For that you need a recursive tool, such as find.
find FOLDER -type f -delete 0 With bash:
shopt -s globstar ## Enables recursive globbing
for f in FOLDER/**/*; do [[ -f $f ]] && echo rm -- "$f"; doneHere iterating over the glob expanded filenames, and removing only files.
The above is dry-run, if satisfied with the changes to be made, remove echo for actual removal:
for f in FOLDER/**/*; do [[ -f $f ]] && rm -- "$f"; doneFinally, unset globstar:
shopt -u globstarWith zsh, leveraging glob qualifier:
echo -- FOLDER/**/*(.)(.) is glob qualifier, that limits the glob expansions to just regular files.
The above will just print the file names, for actual removal:
rm -- FOLDER/**/*(.) 1 If your version of find doesn't support -delete you can use the following to delete every file in the current directory and below.
find . ! -type d -exec rm '{}' \; 6