如何特别使用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?
问题描述
到目前为止,我有这个:
So far I have this:
find -name ".txt"
我不太确定如何使用wc来查找确切的文件数.使用上面的命令时,所有.txt文件都会显示,但我需要扩展名为.txt的文件的确切 number .请不要建议使用其他命令,因为我想专门使用 find 和 wc .谢谢
I'm not quite sure how to use wc to find out the exact number of files. When using the command above, all the .txt files show up, but I need the exact number of files with the .txt extension. Please don't suggest using other commands as I'd like to specifically use find and wc. Thanks
推荐答案
尝试:
find . -name '*.txt' | wc -l
wc
的-l
选项告诉它仅返回行数.
The -l
option to wc
tells it to return just the number of lines.
如果任何.txt文件名包含换行符,则上面的代码将输入错误.它将与任何文件名一起正常工作:
The above will give the wrong number if any .txt file name contains a newline character. This will work correctly with any file names:
find . -iname '*.txt' -printf '1\n' | wc -l
-printf '1\n
告诉find
为找到的每个文件名仅打印行1
.这样可以避免文件名中包含难以识别的字符的问题.
-printf '1\n
tells find
to print just the line 1
for each file name found. This avoids problems with file names having difficult characters.
让我们创建两个.txt
文件,一个文件的名称中包含换行符:
Let's create two .txt
files, one with a newline in its name:
$ touch dir1/dir2/a.txt $'dir1/dir2/b\nc.txt'
现在,让我们找到find命令:
Now, let's find the find command:
$ find . -name '*.txt'
./dir1/dir2/b?c.txt
./dir1/dir2/a.txt
要计数文件:
$ find . -name '*.txt' | wc -l
3
如您所见,答案只有一个.但是,改进的版本可以正常工作:
As you can see, the answer is off by one. The improved version, however, works correctly:
$ find . -iname '*.txt' -printf '1\n' | wc -l
2
这篇关于如何特别使用find命令和wc命令查找目录和所有子目录中所有.txt文件的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!