开发者

sample Bash script or command to retrieve number files in directory

开发者 https://www.devze.com 2023-03-01 02:32 出处:网络
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 su

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 ? Thanks for advice.


try this

targetDir=/test
find ${targetDir} -type f | wc -l

I hope this helps.


$(ls -lR /test | grep '^-' | wc -l)

Better to use find

$(find /test -type f | wc -l)


the standard way is to use find

find /test -type f | wc -l

Other methods include using the shell (eg 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

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:

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"
0

精彩评论

暂无评论...
验证码 换一张
取 消