0

I have a large number of directories, and I want to count with bash commands the number of directories in each of these directories. I am having a hard time piping ls and wc to achieve what I want.

E.g., if I have the following folder structure (where the leaf folders might contain further subfolders):

.
├── folder1
│   └── subfoldera
├── folder2
│   ├── subfoldera
│   └── subfolderb
├── folder3
│   ├── subfoldera
│   ├── subfolderb
│   └── subfolderc
└── folder4
    ├── subfoldera
    ├── subfolderb
    └── subfolderc

Then I wish to have the counts

1
2
3
3

and so on.

1
3

With bash and arrays:

dirs=(*/)                      # get all directories with globbing
                               # in current directory

for d in "${dirs[@]}"; do
  sub=("$d"*/)                 # get all subdirs in $d
  echo "${#sub[@]}"            # print number of array elements/subdirs
done

Output:

1
2
3
3

As one line:

dirs=(*/); for d in "${dirs[@]}"; do sub=("$d"*/); echo "${#sub[@]}"; done
4
  • Thank you! and thanks for the tip in the comment above. – GZ- Aug 17 '20 at 21:07
  • To avoid problems with e.g. blanks in the names, I have fixed the code. – Cyrus Aug 17 '20 at 21:17
  • why does the (*/) need to be in parenthesis ? – Akuseru Aug 17 '20 at 21:33
  • 1
    @Akuseru: To declare dirs as an array and no string. See output of dirs=(*/); declare -p dirs. – Cyrus Aug 17 '20 at 21:43
0

If the names of the dirs do not contain '\n' this should work:

parallel 'ls -d {}/*/ | wc -l' ::: */

If you want to include the dir in the output:

parallel --tag 'ls -d {}/*/ | wc -l' ::: */

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.