简体   繁体   中英

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 ? 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 /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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM