从命令行计算多个子目录中的文件数 [英] Counting number of files in multiple subdirectories from command line

查看:91
本文介绍了从命令行计算多个子目录中的文件数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含大量子目录的目录。每个子目录的名称都类似 treedir_xxx,其中xxx是数字。我想运行一个命令(最好是从命令行开始,因为我没有批处理脚本的经验),该命令将计算每个名为 treedir_xxx的子目录中的文件数,并将这些数字写入文本文件。我觉得这应该不是很困难,但到目前为止我一直没有成功。

I have a directory which contains a large number of subdirectories. Each subdirectory is named something like "treedir_xxx" where xxx is a number. I would like to run a command (preferably from the command line as I have no experience with batch scripts) that will count the number of files in each subdirectory named 'treedir_xxx' and write these numbers to a text file. I feel this should not be very difficult but so far I have been unsuccessful.

我尝试过类似 find * treedir * -maxdepth 1 -type f | wc -l <​​/ code>,但这仅返回文件总数,而不是每个单独文件夹中的文件数。

I have tried things like find *treedir* -maxdepth 1 -type f | wc -l however this just returns the total number of files rather than the number of files in each individual folder.

推荐答案

使用 for 循环代替使用查找。我假设您使用的是 bash 或类似的东西,因为这是大多数现代Linux发行版中最常见的shell:

Instead of using find, use a for loop. I am assuming that you are using bash or similar since that is the most common shell on most of the modern Linux distros:

for i in treedir_*; do ls "$i" | wc -l; done

给出以下结构:

treedir_001
 |__ a
 |__ b
 |__ c
treedir_002
 |__ d
 |__ e
treedir_003
 |__ f

结果是:

3
2
1

您可以花哨并在数字周围打印任何内容:

You can get fancy and print whatever you want around the numbers:

for i in treedir_*; do echo $i: $(ls "$i" | wc -l); done

给予

treedir_001: 3
treedir_002: 2
treedir_003: 1

这使用 $(...)来获取命令的输出作为字符串并将其传递给 echo ,然后可以将所有内容打印在一行上。

This uses $(...) to get the output of a command as a string and pass it to echo, which can then print everything on one line.

for i in treedir_*; do echo $i; ls "$i" | wc -l; done

给予

treedir_001
3
treedir_002
2
treedir_003
1

此示例说明在单个循环中使用多个命令。

This one illustrates the use of multiple commands in a single loop.

用于可以像其他任何命令一样重定向到文件或通过管道传递,因此您可以在treedir_ *中为我执行

for can be redirected to a file or piped just like any other command, so you can do

for i in treedir_*; do ls "$i" | wc -l; done > list.txt

或更好

for i in treedir_*; do ls "$i" | wc -l; done | tee list.txt

第二个版本将输出发送到程序 tee ,将其打印到标准输出,并将其重定向到文件。有时,与使用> 进行简单重定向相比,调试起来更好。

The second version sends the output to the program tee, which prints it to standard output and also redirects it to a file. This is sometimes nicer for debugging than a simple redirect with >.

find 是一把强大的锤子,但并非所有东西都是钉子...

find is a powerful hammer, but not everything is a nail...

这篇关于从命令行计算多个子目录中的文件数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆