Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count total directories and files in all sub directories unix [duplicate]

I am trying to get a count of the subdirectories and all the files total in all the subdirectories within a directory in Unix. I tried this:

ls -lR | grep ^d | wc -l

but that just gives me the total subdirectories, not the total files. How would I modify this or is there a way to find out both numbers from one command? Or should I split this into two?

like image 787
Will Avatar asked Nov 16 '25 03:11

Will


1 Answers

Because files may contain newlines or spaces or the like, the best method is to use find but instead of having it print the names of the files have it print a . or similar for every file found. That solution would look like

find . -type d -or -type f -printf '.' | wc -c

which will search starting in the current directory for any -type d or -type f which is directory or file. For each it'll print . and then we count the number of characters printed.

like image 52
Eric Renouf Avatar answered Nov 17 '25 22:11

Eric Renouf