[英]sample Bash script or command to retrieve number files in directory
I have problem with number of files in directory 我目录中的文件数有问题
I use 我用
$(ls /test -l | grep '^-' | wc -l)
but this way I retrieve just number of files in the same path but don't retrieve number of files in subdirectors if I have 但是通过这种方式,我只检索同一路径中的文件数量,但是如果我有子目录,则不会检索子目录中的文件数量
/test/1
/test/1/2
/test/1/3
/test/1/4/1
/test/1/4/2
/test/1/5
my question is how to retrieve number of files in /test ? 我的问题是如何在/ test中检索文件数量? Thanks for advice.
谢谢你的建议。
try this 尝试这个
targetDir=/test
find ${targetDir} -type f | wc -l
I hope this helps. 我希望这有帮助。
$(ls -lR /test | grep '^-' | wc -l)
更好地使用查找
$(find /test -type f | wc -l)
the standard way is to use find
标准方法是使用
find
find /test -type f | wc -l
Other methods include using the shell (eg bash 4) 其他方法包括使用外壳(例如bash 4)
shopt -s globstar
shopt -s dotglob
declare -i count=0
for file in **
do
if [ -f "$file" ];then
((count++))
fi
done
echo "total files: $count"
Or a programming language, such as Perl/Python or Ruby 或一种编程语言,例如Perl / Python或Ruby
ruby -e 'a=Dir["**/*"].select{|x|File.file?(x)};puts a.size'
Using wc -l
is the easiest way, but if you want to count files accurately it's more complicated: 使用
wc -l
是最简单的方法,但是如果您想准确地计数文件,则更为复杂:
count_files()
{
local file_count=0
while IFS= read -r -d '' -u 9
do
let file_count=$file_count+1
done 9< <( find "$@" -type f -print0 )
printf %d $file_count
}
As a bonus you can use this to count in several directories at the same time. 另外,您可以使用它来同时计入多个目录。
To test it: 要测试它:
test_dir="$(mktemp -d)"
touch "${test_dir}/abc"
touch "${test_dir}/foo
bar
baz"
count_files "$test_dir"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.