Linux命令行:获取顶层目录文件数,含空子目录的零文件目录
顶层目录文件数统计方案(含空子目录的零文件目录)
之前两个命令的局限性:
find . -maxdepth 1 -type d -empty仅识别完全空的顶层目录(连空子目录都没有的),会跳过「顶层目录→二级空子目录」这类结构find . -type f | cut -d/ -f2 | sort | uniq -c | sort -nr只统计包含文件的顶层目录,遗漏了所有子目录均为空的零文件顶层目录
方案一:循环遍历统计
直接遍历所有顶层目录,逐个统计其下的普通文件总数:
for dir in */; do count=$(find "$dir" -type f | wc -l) echo "${dir%/} $count" done
*/自动匹配当前目录下所有顶层目录(排除文件)${dir%/}移除目录名末尾的斜杠,让输出格式更整洁find "$dir" -type f | wc -l递归统计目录下所有普通文件数量,空子目录结构会返回0
方案二:find+批量处理(适配特殊目录名)
适合处理含空格、特殊字符的目录,避免解析错误:
find . -mindepth 1 -maxdepth 1 -type d -print0 | xargs -0 -I {} sh -c 'echo "{} $(find {} -type f | wc -l)"' | sed 's/\.\///'
-print0和xargs -0配合,解决目录名含特殊字符时的解析问题sed 's/\.\///'移除目录名前的./前缀,让输出更清爽
示例输出
- dir1 0
- dir2 5
- dir3 0
- dir4 26
内容的提问来源于stack exchange,提问作者Kilgore Trout
相关产品推荐
相关产品推荐

