简体   繁体   中英

Recursively find directories by a specific name and then clear them

Suppose that the following project structure is given:

/
|
|- /bin
|- /src
     |
     |- /bin
     |- abc
         ...
         |
         |- /bin

and I would like to erase the contents of the bin subdirectories, but not delete them. How do I achieve tis through the Bash command line?

EDIT

I have tried find . -regex bin/* -type d -exec rm -rf {} \\; find . -regex bin/* -type d -exec rm -rf {} \\; , but to no avail.

I suggest with GNU find:

find . -regex ".*/bin/.*" -type f -exec echo rm {} \;

if everything looks fine remove echo .

When you want to delete files, it is unnecessary (indeed dangerous) to pass -r to rm .

Besides, find "knows" how to delete, without the need to call rm in the first place.

find . -type f -wholename "*/bin/*" -delete

Debug your command: try each argument to find in isolation to see if it is producing expected output.

We quickly see that

find . -regex bin/*

doesn't work because of an issue in regex. If we check the man for find, we see that the regex must match the full path:

-regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3', you can use the regular expression .*bar.' or .*b.*3', but not f.*r3'.

This should do the job:

find . -regex '".*/bin/.*"' -type d -delete

or using your command:

find . -regex '".*/bin/.*"' -type d -prune -exec rm -rf {} \;

Remember to quote your expressions to avoid unexpected shell expansion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM