4

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?

kvantour
  • 25,269
  • 4
  • 47
  • 72
Will
  • 99
  • 1
  • 8

1 Answers1

8

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.

Eric Renouf
  • 13,950
  • 3
  • 45
  • 67