使用 Unix 命令计算多个文件夹中的文件数
Count number of files in several folders with Unix command
我想统计每个文件夹中的文件数量。对于一个文件夹,我可以这样做:
find ./folder1/ -type f | wc -l
我可以为每个文件夹(folder2、folder3、...)重复此命令,但我想知道是否可以通过一个命令获取信息。输出应如下所示:
folder1 13
folder2 4
folder3 1254
folder4 327
folder5 2145
我可以通过以下方式获取我的文件夹列表:
find . -maxdepth 1 -type d
哪个returns:
./folder1
./folder2
./folder3
./folder4
./folder5
然后,我想把这个命令和第一个命令结合起来,但我不知道具体怎么做。也许用“-exec”或“xargs”?
非常感谢。
使用 xargs
的一个可能的解决方案是使用 -I
选项,它会替换 replace-str
(下面代码示例中的 %
)从标准输入中读取名称的参数:
find . -maxdepth 1 -type d -print0 | xargs -0 -I% sh -c 'echo -n "%: "; find "%" -type f | wc -l'
你还需要将find
命令传递给sh
,如果你想用wc
管道它,否则wc
将计算所有目录中的文件。
另一种解决方案(可能不那么神秘)是使用单行 for
循环:
for d in */; do echo -n "$d: "; find "$d" -type f | wc -l; done
我想统计每个文件夹中的文件数量。对于一个文件夹,我可以这样做:
find ./folder1/ -type f | wc -l
我可以为每个文件夹(folder2、folder3、...)重复此命令,但我想知道是否可以通过一个命令获取信息。输出应如下所示:
folder1 13
folder2 4
folder3 1254
folder4 327
folder5 2145
我可以通过以下方式获取我的文件夹列表:
find . -maxdepth 1 -type d
哪个returns:
./folder1
./folder2
./folder3
./folder4
./folder5
然后,我想把这个命令和第一个命令结合起来,但我不知道具体怎么做。也许用“-exec”或“xargs”?
非常感谢。
使用 xargs
的一个可能的解决方案是使用 -I
选项,它会替换 replace-str
(下面代码示例中的 %
)从标准输入中读取名称的参数:
find . -maxdepth 1 -type d -print0 | xargs -0 -I% sh -c 'echo -n "%: "; find "%" -type f | wc -l'
你还需要将find
命令传递给sh
,如果你想用wc
管道它,否则wc
将计算所有目录中的文件。
另一种解决方案(可能不那么神秘)是使用单行 for
循环:
for d in */; do echo -n "$d: "; find "$d" -type f | wc -l; done