How to remove folders with a certain name
Asked Answered
D

12

269

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?

Doubletalk answered 23/10, 2012 at 14:26 Comment(1)
Perhaps missing the point but maybe it does assist someone: I have 410 folders in a main folder - each of the 410 with two sub-folders. All first sub-folders are named 'final' and contains edited pdfs and a Word content list. All the second sub-folders named tif_pdf_various_names contains originally scanned saved-to tiff files (some up to 200 pages), their un-edited pdfs and a draft .docx content list - thus a home work collection. I needed to make a collection of the 410 folders containing only the finally edited material - with the tiffs close to 4TB. Easiest method found was to use (in MicrMocambique
C
281

If the target directory is empty, use find, filter with only directories, filter by name, execute rmdir:

find . -type d -name a -exec rmdir {} \;

If you want to recursively delete its contents, replace -exec rmdir {} \; with -delete or -prune -exec rm -rf {} \;. Other answers include details about these versions, credit them too.

Chansoo answered 23/10, 2012 at 14:29 Comment(4)
Could you please explain what {} \; does?Mitrewort
{} can be read as "for each matching file/ folder" - i.e. it substitutes for each "found" file/ folder. \; is a terminator for the -exec clause.Loreeloreen
This gives me a "cannot delete" error when the directory is not emptySurmullet
Consider adding -prune flag to the answer as per @David Grayson suggestion. Without this, find will still try to visit the now missing folder and will eventually exit with an error code, which can e.g. fail a Docker build.Frederickfredericka
L
258

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.

Loreeloreen answered 23/10, 2012 at 14:28 Comment(6)
You probably want to add a "-type d" in there just incase a file matches the same name.Yester
Also note that this will catch something like 1/2/a/3/4, which may not be intended, so +1 for the recommendation to test first...Sibship
reco echo {} to test it first, instead of ls {}Velodrome
Here go my node_modules/.Compatriot
I used find . -name a -type d -exec rm -rf {} \; and it worked, although it printed out find: ‘./subdir/subdir/a’: No such file or directory for each directory deleted.Feigin
The 'No such file or directory' error comes from find because it tries to continue finding in that same folder you just removed. Use -prune to prevent that and shut it up.Seisin
P
117

This also works - it will remove all the folders called "a" and their contents:

rm -rf `find . -type d -name a`
Postmillennialism answered 16/10, 2014 at 16:54 Comment(6)
@Buffalo, how come? This defo works but so do the others. Would be surprised to find an env where this works but the others don't given all answers are essentially find/rm.Loreeloreen
@Loreeloreen because if you do find . -name a -exec rm -rf {} \;, find will crash when it tries to enter that directory to look for more items, giving you an error like find: '1/2/3/a': No such file or directory.Guillemette
@Alex Grönholm sure, but all folders named 'a' are nevertheless deleted. As you state, find can't subsequently look inside a deleted 'a' folder but that doesn't matter. Wanting to keep content of 'a' for subsequent processing before delete is a different use-case to what the OP asked.Loreeloreen
@Loreeloreen Yes, the directories are deleted but I don't think it's good to recommend a solution where the command fails (returns a nonzero exit code).Guillemette
This was giving me an error illegal option --t. I had to also pass the directory to search in (#25841213): rm -rf `find . -type d -name a`.Kaliope
I need to add a . --> rm -rf `find . -type d -name a`Stagehand
A
68

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

Agrippina answered 3/10, 2018 at 16:8 Comment(3)
Ahh that worked nicely, to make this something you could use with ease you could save this as a little shellscript: sh #!/bin/bash echo "Found node_modules: "; find -type d -name node_modules -prune; read -r -p "Do you really want to delete all directories? [yes/no] " input; if [ ! $input != "yes" ]; then find -type d -name node_modules -prune -exec rm -rf {} \;; fi Cressida
On my Macbook Pro, when I ran your command, I got "illegal option -- t". So I added a dot. My command: find . -type d -name node_modules -prune -exec rm -rf {} \;Quinquefid
And this is why I'm switching to pnpm just cleared over 150gb on my computer. Thanks for this one.Dutyfree
C
38

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.

Chitwood answered 3/12, 2016 at 8:1 Comment(0)
H
23

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

Headphone answered 30/10, 2019 at 17:32 Comment(1)
exactly what I was looking for -- thanks!Gaud
A
16
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.

Anechoic answered 23/10, 2012 at 14:35 Comment(2)
Oh, just that teeny tiny risk. Is that all? Haha. Super thanks for the warning. I definitely would make that typing mistake.Questionable
I like the xargs approach because it's easy to understand and easy to dry-run. You can solve the 'WARNING' issue by using -print0 and '-0' (as demonstrated here). For example: find -type d -iname ".recycle" -print0 |xargs -0 -n1 rm -rfSubmiss
H
16

Combining multiple answers, here's a command that works on both Linux and MacOS

rm -rf $(find . -type d -name __pycache__)
Hydrastine answered 20/8, 2019 at 15:40 Comment(1)
Only one that worked for me that didnt also throw errorsCoyotillo
L
13

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 {} \;
Liva answered 9/6, 2016 at 13:30 Comment(0)
F
7

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)
Fons answered 12/5, 2017 at 12:3 Comment(1)
This answer only works for empty folders. -delete does not remove non-empty folders.Glavin
F
4

Earlier comments didn't work for me since I was looking for an expression within the folder name in some folder within the structure

The following works for a folder in a structure like:

b/d/ab/cd/file or c/d/e/f/a/f/file

To check before using rm-rf

find . -name *a* -type d -exec realpath {} \;

Removing folders including content recursively

find . -name *a* -type d -exec rm  -rf {} \;
Freedom answered 1/3, 2022 at 3:41 Comment(0)
O
-2

find path/to/the/folders -maxdepth 1 -name "my_*" -type d -delete

Octillion answered 6/11, 2017 at 12:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.