Skip to main content

Remove file or folder recursively

· One min read
Hung Viet Nguyen

How to remove files and folders with a name pattern recursively?

Remove files recursively

  • Dry run
find . -name "\*.bak" -type f
  • Remove
find . -name "\*.bak" -type f -delete

https://askubuntu.com/questions/377438/how-can-i-recursively-delete-all-files-of-a-specific-extension-in-the-current-di

Remove folders recursively

  • Dry run
find . -name 'node_modules' -type d -prune

If you want to remove all dist folders, but not in node_modules:

find . -name 'dist' -not -path "./node_modules/\*" -type d -prune
  • Remove
find . -name 'node_modules' -type d -prune -exec rm -rf '{}' +

Reference

https://stackoverflow.com/questions/42950501/delete-node-modules-folder-recursively-from-a-specified-path-using-command-line