In Linux, how do I remove folders with a certain name which are nested deep in a folder hierarchy?
The following paths are under a folder and I would like to remove all folders named a
.
1/2/3/a
1/2/3/b
10/20/30/a
10/20/30/b
100/200/300/a
100/200/300/b
What Linux command should I use from the parent folder?
find path/to/the/folders -maxdepth 1 -name "my_*" -type d -delete
This command works for me. It does its work recursively
find . -name "node_modules" -type d -prune -exec rm -rf '{}' +
. - current folder
"node_modules" - folder name
Use find for name "a" and execute rm to remove those named according to your wishes, as follows:
find . -name a -exec rm -rf {} \;
Test it first using ls to list:
find . -name a -exec ls {} \;
To ensure this only removes directories and not plain files, use the "-type d" arg (as suggested in the comments):
find . -name a -type d -exec rm -rf {} \;
The "{}" is a substitution for each file "a" found - the exec command is executed against each by substitution.
This also works - it will remove all the folders called "a" and their contents:
rm -rf `find -type d -name a`
I had more than 100 files like
log-12
log-123
log-34
....
above answers did not work for me
but the following command helped me.
find . -name "log-*" -exec rm -rf {} \;
i gave -type
as .
so it deletes both files and folders which starts with log-
and rm -rf
deletes folders recursively even it has files.
if you want folders alone
find -type d -name "log-*" -exec rm -rf {} \;
files alone
find -type f -name "log-*" -exec rm -rf {} \;
Another one:
"-exec rm -rf {} \;" can be replaced by "-delete"
find -type d -name __pycache__ -delete # GNU find
find . -type d -name __pycache__ -delete # POSIX find (e.g. Mac OS X)
Combining multiple answers, here's a command that works on both Linux and MacOS
rm -rf $(find . -type d -name __pycache__)
find ./ -name "FOLDERNAME" | xargs rm -Rf
Should do the trick. WARNING, if you accidentally pump a .
or /
into xargs rm -Rf
your entire computer will be deleted without an option to get it back, requiring an OS reinstall.
To delete all directories with the name foo
, run:
find -type d -name foo -a -prune -exec rm -rf {} \;
The other answers are missing an important thing: the -prune
option. Without -prune
, GNU find will delete the directory with the matching name and then try to recurse into it to find more directories that match. The -prune
option tells it to not recurse into a directory that matched the conditions.
I ended up here looking to delete my node_modules
folders before doing a backup of my work in progress using rsync
. A key requirements is that the node_modules
folder can be nested, so you need the -prune
option.
First I ran this to visually verify the folders to be deleted:
find -type d -name node_modules -prune
Then I ran this to delete them all:
find -type d -name node_modules -prune -exec rm -rf {} \;
Thanks to pistache
Source: Stackoverflow.com