递归地指出目录中的文件数

时间:2014-03-10 16:48:25

标签: bash shell find

查找包含超过给定数量的文件xyz的根目录下的所有目录(假设xyz为1000)并将返回的数字和目录的输出保存在文件中的命令是什么? (或更好:变量)?

2 个答案:

答案 0 :(得分:2)

使用finddirname

$DIR=/root/dir/to/search     
find "$DIR" -type f -exec dirname {} \; | uniq -c | sort -rn | awk '$1>=1000{print}'

递归查找当前目录下的所有文件,然后截断文件名以仅保留每个文件的父目录。这些已经排序,因此uniq -c将计算每个目录包含的文件数,awk仅打印超过1000个文件的文件。

将结果保存在文件中:

find "$DIR" ... | awk '$1>=1000{print}' > file.txt

保存在变量中:

var=$(find "$DIR" ... | awk '$1>=1000{print}')

答案 1 :(得分:0)

find . -type d | while read dir; do
    printf '%d\t%s\n' $(find "$dir" -maxdepth 1 -type f | wc -l) "$dir"
done | sort -rn

这将打印每个目录以及其中的文件数量。它对它们进行排序,使得文件最多的文件是第一个。

如果要将打印输出限制为至少包含$limit个文件的目录,请执行以下操作:

find . -type d | while read dir; do
    count=$(find "$dir" -maxdepth 1 -type f | wc -l)
    (($count >= $limit)) && printf '%d\t%s\n' "$count" "$dir"
done | sort -rn

为了使这个更加强大并处理包含空格和其他特殊字符的异常文件名,请向findread添加一些标记。从技术上讲,文件名允许包含选项卡和换行符,因此最好以防御方式编写脚本,这样这些类型的文件名不会导致问题。

find . -type d -print0 | while read -d $'\0' -r dir; do
    count=$(find "$dir" -maxdepth 1 -type f -exec echo \; | wc -l)
    (($count >= $limit)) && printf '%d\t%s\n' "$count" "$dir"
done | sort -rn