Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove folders with a certain name

Tags:

linux

unix

rm

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?

like image 757
Joe Avatar asked Oct 15 '22 04:10

Joe


People also ask

How do I delete a file with a specific name?

Type the rm command, a space, and then the name of the file you want to delete. If the file is not in the current working directory, provide a path to the file's location. You can pass more than one filename to rm . Doing so deletes all of the specified files.

How do I delete a specific folder?

To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r . Directories that are removed with the rmdir command cannot be recovered, nor can directories and their contents removed with the rm -r command.

How do you mass remove items from folders?

Ctrl + A, Highlight all the files (that you want to move) and right click ---> Cut. As you saw, over 36000 . mp3 files were taken out of 6,000 Subfolders. Imagine doing this manually for each folder.


2 Answers

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.

like image 170
pistache Avatar answered Oct 26 '22 11:10

pistache


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.

like image 42
wmorrison365 Avatar answered Oct 26 '22 11:10

wmorrison365