如何使用 find 命令和 wc 命令查找目录和所有子目录中所有 .txt 文件的数量?

How do I find the number of all .txt files in a directory and all sub directories using specifically the find command and the wc command?

到目前为止我有这个:

find -name ".txt"

我不太清楚如何使用 wc 找出确切的文件数。使用上面的命令时,会显示所有 .txt 文件,但我需要确切的 数量 扩展名为 .txt 的文件。请不要建议使用其他命令,因为我想专门使用 findwc。谢谢

find -type f -name "*.h" -mtime +10 -print | wc -l

这成功了。

尝试:

find . -name '*.txt' | wc -l

wc-l 选项告诉它 return 只是行数。

改进(需要 GNU find)

如果任何 .txt 文件名包含换行符,以上将给出错误的数字。这将适用于任何文件名:

find . -iname '*.txt' -printf '1\n' | wc -l

-printf '1\n 告诉 find 只为找到的每个文件名打印行 1。这避免了文件名包含困难字符的问题。

例子

让我们创建两个 .txt 文件,其中一个文件的名称中包含换行符:

$ touch dir1/dir2/a.txt $'dir1/dir2/b\nc.txt'

现在,让我们找到查找命令:

$ find . -name '*.txt'
./dir1/dir2/b?c.txt
./dir1/dir2/a.txt

要统计文件:

$ find . -name '*.txt' | wc -l
3

如您所见,答案相差一个。然而,改进后的版本可以正常工作:

$ find . -iname '*.txt' -printf '1\n' | wc -l
2