删除所有少于X个文件的子文件夹

时间:2018-09-13 13:35:20

标签: bash terminal find

我想删除文件夹中X文件少于所有的子文件夹

以下代码搜索少于X个文件的那些子文件夹:

$ find . -type d -exec sh -c 'set -- "$0"/*; [ $# -le 10 ]' {} \; -print
./digna_1919
./digna_2040
./digna_1682
(more output omitted) 

所以我可以找到他们!但是,如果这样做,我将得到“目录不为空”:

$ find . -type d -exec sh -c 'set -- "$0"/*; [ $# -le 10 ]' {} \; -delete
find: cannot delete ‘./digna_1919’: Directory not empty
find: cannot delete ‘./digna_2040’: Directory not empty
find: cannot delete ‘./digna_1682’: Directory not empty
(more output omitted)

如果执行此操作,则会显示“无此文件或目录”:

$ find . -type d -exec sh -c 'set -- "$0"/*; [ $# -le 10 ]' {} \; -exec rm -r "{}" \;
find: ‘./digna_1919’: No such file or directory
find: ‘./digna_2040’: No such file or directory
find: ‘./digna_1682’: No such file or directory
(more output omitted)

我在哪里做错了?非常感谢!

Source of the code

1 个答案:

答案 0 :(得分:0)

使用-depth使find在目录本身之前处理每个目录的内容。每当您删除项目时,您都希望这样做。

$ find . -depth -type d -exec sh -c 'set -- "$0"/*; [ $# -le 10 ]' {} \; -exec rm -r {} \;