ubuntu22查看文件下子文件夹的数量
在 Ubuntu 22.04(或其它 Linux 发行版)里,可以通过几种方式查看某个目录下子文件夹的数量。下面给你几种常见方法:
1. ls + grep + wc
ls -l /path/to/dir | grep ^d | wc -l
ls -l显示目录详情grep ^d筛选出以d开头(表示目录)的行wc -l统计行数,即子目录数量
⚠️ 这种方式只统计一级子目录。
2. 使用 find(推荐)
find /path/to/dir -mindepth 1 -maxdepth 1 -type d | wc -l
-mindepth 1表示不包括当前目录本身-maxdepth 1限制只看一层-type d表示目录wc -l统计数量
这个方法最准确,而且不会受 ls 输出格式影响。
3. tree
如果安装了 tree 工具:
tree -d -L 1 /path/to/dir | tail -n 1
-d只显示目录-L 1限制层级为一层- 最后一行会显示“X directories”,即子目录数量
如果没装,可以先安装:
sudo apt install tree
