我删除了
ls
方法不可靠(
ls
它不仅输出目录中的文件,还输出目录名和总计,这些都不应该包含在目录或文件中)。
我更改了Perl方法以利用
postprocess
该函数仅在离开目录时运行,因此不需要对文件类型进行测试。
我也修复了
tree
方法:至少在我的系统上,
树
需要
-a
包含以点开头的文件名。您可以使用
awk
对于文件和目录,无需计算行数。
# Methods to count directories
dir_methods=(
"Directory Method 1 (find): find '$dir' -type d | wc -l"
"Directory Method 2 (tree): tree -afi '$dir' | tail -n 1 | awk '{print \$1}'"
"Directory Method 5 (bash loop): count=0; for d in \$(find '$dir' -type d); do count=\$((count + 1)); done; echo \$count"
"Directory Method 6 (perl): perl -MFile::Find -le 'find({wanted => sub {}, postprocess => sub { ++\$n }}, \"$dir\"); print \$n'"
"Directory Method 7 (python): python3 -c 'import os; print(sum([len(dirs) for _, dirs, _ in os.walk(\"$dir\")]))'"
)
# Methods to count files
file_methods=(
"File Method 1 (find): find '$dir' -type f | wc -l"
"File Method 2 (tree): tree -a '$dir' | tail -n1 | awk '{print \$3}'"
"File Method 4 (bash loop): count=0; for f in \$(find '$dir' -type f); do count=\$((count + 1)); done; echo \$count"
"File Method 5 (perl): perl -MFile::Find -le 'find({wanted => sub { ++\$n },postprocess => sub {--\$n}}, \"$dir\"); print \$n'"
"File Method 6 (python): python3 -c 'import os; print(sum([len(files) for _, _, files in os.walk(\"$dir\")]))'"
)
不过,结果仍然不一样:在计算目录时,python和tree不计算顶级目录。
如果文件或目录的名称中有空格,“bash循环”方法会分别计算每个单词,所以这是错误的。
如果文件或目录的名称中有换行符,即使是
find
方法不对。您可以通过根本不打印名称来修复它:
"Directory Method 1 (find): find '$dir' -type d -printf '\\n' | wc -l"
文件也是如此。你可以用同样的方法修复“bash循环”。