简体   繁体   English

以特定名称递归查找目录,然后清除它们

[英]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. 我想删除bin子目录的内容,但不删除它们。 How do I achieve tis through the Bash command line? 如何通过Bash命令行实现tis?

EDIT 编辑

I have tried find . -regex bin/* -type d -exec rm -rf {} \\; 我试图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: 我建议与GNU查找:

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

if everything looks fine remove echo . 如果一切正常,则删除echo

When you want to delete files, it is unnecessary (indeed dangerous) to pass -r to rm . 当您要删除文件时,没有必要(确实很危险)将-r传递给rm

Besides, find "knows" how to delete, without the need to call rm in the first place. 此外,无需首先调用rm ,即可find “知道”如何删除的信息。

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

Debug your command: try each argument to find in isolation to see if it is producing expected output. 调试您的命令:尝试单独find每个参数,以查看其是否产生预期的输出。

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. -regex模式文件名与正则表达式模式匹配。 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.' 例如,要匹配名为./fubar3', you can use the regular expression的文件./fubar3', you can use the regular expression 。* bar。 or .*b.*3', but not f.*r3'. .*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. 请记住用引号引起来,以避免意外的shell扩展。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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