command line – How to count subfolders containing numbers?


If you want to count all sub directories of the current directory whose name contains at least one number, you can do:

$ set -- *[0-9]*/
$ echo $#

For example, given this input:

$ ls -F
1/  123dir/  bar/  di32r/  dir1/  file  file1  file2  file3  myfile.txt

Where we have 4 directories whose names contain at least one digit, the commands above return:

$ set -- *[0-9]*/ && echo $#
4

This uses the $@ builtin array, but you can use an explicitly named one too:

$ numdirs=(*[0-9]*/)
$ echo "${#numdirs[@]}"
4

The idea is simply to populate an array with all elements matching the glob *[0-9]*/ (0 or more characters, a number, 0 or more characters and a / to limit to directories) and then print the length of an array (given an array named array in bash, ${#array[@]} is the number of elements in that array).



Source link

Leave a Comment