How can I use Terminal to count all direct subfolders in a directory that contain numbers?

So it shouldn't be counted recrusively.

  • 5
    What does "containing numbers" mean? Do you mean folders whose name is a number?Do you mean folders containing files whose names are numbers? Does that mean numbers only or would something like file1 also count? How about extensions, should .3.txt be counted? And is having at least one such file enough for the folder to be counted or do you want to count only folders containing nothing but numerical file names? Please edit your question and clarify.
    – terdon
    Feb 12 at 9:47
  • 2
    Please address the questions I asked too. We need to know what you are looking for.
    – terdon
    Feb 12 at 12:52

2 Answers 2


You can run the following command, that relies on find and wc, either from withing the directory inside which you wish to count the subdirectories (find .) or by replacing find . by the path to the directory you want to count subdirectories in (find /path/to/directory):

find . -maxdepth 1 -type d -name "*[0-9]*" -printf "." | wc -c

This command:

  • finds directories only (-type d)
  • searching only one level deep (-maxdepth 1)
  • that contain at least one numerical digit anywhere in their name (-name "*[0-9]*")
  • then prints a . for any file found (-printf ".")
  • and finally pipe (|) the result to wc -c to count the number of . (actually byte counts), which corresponds to the total number of directories found.



To count non hidden subfolders in the current directory whose names contain at least one digit, you can use one of the following

In bash:

shopt -s nullglob
dirs=( *[[:digit:]]*/ )
printf '%d\n' "${#dirs[@]}"

If you omit the nullglob, it will return a count of 1 in the case that there are no matching subdirs. In POSIX sh (which doesn't have a nullglob equivalent) we need to check explicitly that we are not just counting the unmatched pattern:

set -- *[[:digit:]]*/
[ -d "$1" ] && printf '%d\n' "$#" || printf '0\n'

In either of the above, change [[:digit:]] to [0123456789] if you want to be sure to match Latin decimal digits only. To include hidden (dot) folders in the count in bash, you can set the dotglob option - in POSIX sh, you'd need to explicitly add .*[[:digit:]]*/ I think.

In zsh (this one actually matches a numeric range rather than a single digit):

() { print -rl $# } *<->*(N/)

To include hidden folders in zsh, add the D (dotglob) qualifier.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .