Coder Perfect

How do I delete folders with a certain name?

Problem

How can I delete folders with a certain name that are nested deep in a folder hierarchy in Linux?

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

From the parent folder, what Linux command should I use?

Asked by Joe

Solution #1

Use find, filter with only directories, filter by name, and run rmdir: if the target directory is empty.

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

Replace -exec rmdir ; with -delete or -prune -exec rm -rf -exec rm -rf -exec rm -rf -exec rm -rf -exec rm -rf -exec rm -rf -exec rm -rf -exec rm -rf – Other responses give information about these versions, as well as credit for them.

Answered by pistache

Solution #2

To remove those named according to your wishes, use find for name “a” and rm as follows:

find . -name a -exec rm -rf {} \;

To begin, use ls to create a list:

find . -name a -exec ls {} \;

Use the “-type d” option (as suggested in the comments) to verify that this only removes directories and not ordinary files:

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

The “” is a substitute for each “a” file found, and the exec command is run against each one.

Answered by wmorrison365

Solution #3

This also works, removing all folders with the name “a” and their contents:

rm -rf `find . -type d -name a`

Answered by Arash Fotouhi

Solution #4

I came here to erase my node modules directories before making an rsync backup of my work in progress. One of the most important criteria is that the node modules folder can be nested, which necessitates the use of the -prune option.

First, I ran this to double-check the directories to be erased visually:

find . -type d -name node_modules -prune

Then I ran the following command to remove them all:

find . -type d -name node_modules -prune -exec rm -rf {} \;

Thanks to pistache

Answered by mpalumbo7

Solution #5

Run the following command to remove any folders with the name foo:

find -type d -name foo -a -prune -exec rm -rf {} \;

The -prune option is missing from all of the other solutions. Without -prune, GNU find will remove the matched directory and then try to recurse into it to discover further matching directories. The -prune option instructs it not to recurse into any directories that satisfy the criteria.

Answered by David Grayson

Post is based on https://stackoverflow.com/questions/13032701/how-to-remove-folders-with-a-certain-name