0

I have searched for a solution to listing the number of files in each sub-directory recursively. There are many solutions that will give the number of files in each sub-directory of a given starting directory, but these seem to only list the sub-directory counts of the starting directory, and not recursively going down the tree structure for all sub-directories.

For example,

topdir1

sublevelA1 10 files

  sublevelA2    200 files  

     sublevelA3 600 files  

sublevelB1 50 files

  sublevelB2    123 files  

     sublevelB3 357 files  

The solutions that I have tried will only give me 2 lines saying sublevelA1 810 files and sublevelB1 530 files.

I would like a solution that gives me the 6 lines from above. Indentation is not required.

  • might be worth mentioning if a subfolder should count as file (of its superior folder), or mentioned separately? – Jacob Vlijm Sep 8 at 8:16
  • For me, since accuracy down to the exact number of files is not required, it does not matter if a subfolder is counted as a file or not. – ubnewb Sep 8 at 8:32
0

You could do something like this:

find path/to/topdir1/ -type d -exec sh -c '
  d="$1"; set -- "$d"/*; printf "%s: %d files\n" "$d" "$#"
' sh {} \;

This will print full paths to the subdirectories - if you want the unqualified directory names, change -exec to -execdir. It will include directories in the counts of files.

An alternative might be to use a recursive shell function - note however that this will perform a depth-first search so the order of results may not be what you expect:

#!/bin/sh

_countrecurse() {
  local c=0;
  for f in "$1"/*; do
    if [ -d "$f" ]; then
      _countrecurse "$f";
    else
      c=$(($c+1))
    fi
  done
  printf '%s: %d files\n' "$1" "$c"
}

_countrecurse "$1"

with usage

./countrecurse path/to/topdir1/

This will not include directories in the file counts.

  • Thank you for the "find path/to/topdir1/...." answer. It did the job. – ubnewb Sep 9 at 4:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.