notaproatbash
notaproatbash

Reputation: 456

How can I remove specific directories that all start with a common letter?

I have many EC2 instances in a folder that I need to delete. Using -delete doesn't work because the directories are not empty. I tried looking for a way to get -rmdir -f to work with no success. The instance folders are all started with "i-" which led me to add wildcard "i-*" like that to get it to delete all directories starting with those characters. How can I manage to do this? the directories will never be empty either.

Upvotes: 0

Views: 2196

Answers (3)

dark_77
dark_77

Reputation: 9

To delete the directories matching the pattern graphene-80* directly under /tmp, use

rm -rf /tmp/graphene-80*/

Here, the trailing / ensures that only directories whose names match the graphene-80* pattern are deleted (or symbolic links to directories), and not files etc.

To find the matching directories elsewhere under /tmp and delete them wherever they may be, use

find /tmp -type d -name 'graphene-80*' -prune -exec rm -rf {} +

To additionally see the names of the directories as they are deleted, insert -print before -exec.

The two tests -type d and -name 'graphene-80*' tests for directories with the names that we're looking for. The -prune removes the found directory from the search path (we don't want to look inside these directories as they are being deleted), and the -exec, finally, does the actual removal by means of calling rm.

Upvotes: 0

David Brian
David Brian

Reputation: 1

In the command line interface/shell/born again shell/etc...

rm -r i-*

will remove ANY and ALL contained file(s) or directory(s) with subfiles and sub directories (recursive = -r) where the name begins with "i-" .

Upvotes: 0

stark
stark

Reputation: 13189

Assuming your current dir is the folder in question, how about:

find . -type d -name 'i-*'

If that lists the directories you want to remove, then change it to:

find . -type d -name 'i-*' -exec rm -r {} \;

Upvotes: 1

Related Questions