如何递归地计数Linux目录中的文件?

我发现了这个:

find DIR_NAME -type f ¦ wc -l

但是当我运行它时,它返回以下错误。

查找:路径必须在表达式之前:


当前回答

可以使用ncdu命令。它将递归地计算Linux目录包含多少文件。下面是一个输出示例:

它有一个进度条,如果你有很多文件,这很方便:

在Ubuntu上安装:

sudo apt-get install -y ncdu

基准:我使用https://archive.org/details/cv_corpus_v1.tar(380390个文件,11 GB)作为文件夹,其中必须计算文件的数量。

找到。-type f | wc -l:大约1m20s完成 Ncdu:大约1m20s完成

其他回答

对于当前目录:

find -type f | wc -l

如果你想知道当前目录下每个目录下有多少文件:

for i in */ .*/ ; do 
    echo -n $i": " ; 
    (find "$i" -type f | wc -l) ; 
done

当然,这些都可以写在一行上。括号说明wc -l应该监视谁的输出(在本例中查找$i -type f)。

假设你想要一个每个目录的文件总数,试试:

for d in `find YOUR_SUBDIR_HERE -type d`; do 
   printf "$d - files > "
   find $d -type f | wc -l
done

对于当前目录,尝试这样做:

for d in `find . -type d`; do printf "$d - files > "; find $d -type f | wc -l; done;

如果你有很长的空格名,你需要改变IFS,像这样:

OIFS=$IFS; IFS=$'\n'
for d in `find . -type d`; do printf "$d - files > "; find $d -type f | wc -l; done
IFS=$OIFS

根据上面给出的回复和评论,我列出了下面的文件计数清单。特别是它结合了@Greg Bell提供的解决方案和@Arch Stanton的评论 & @Schneems

计数当前目录和子目录中的所有文件

function countit { find . -maxdepth 1000000 -type d -print0 | while IFS= read -r -d '' i ; do file_count=$(find "$i" -type f | wc -l) ; echo "$file_count: $i" ; done }; countit | sort -n -r >file-count.txt

计数当前目录及子目录中所有给定名称的文件

function countit { find . -maxdepth 1000000 -type d -print0 | while IFS= read -r -d '' i ; do file_count=$(find "$i" -type f | grep <enter_filename_here> | wc -l) ; echo "$file_count: $i" ; done }; countit | sort -n -r >file-with-name-count.txt
tree $DIR_PATH | tail -1

样例输出:

5309个目录,2122个文件