Saturday, January 15, 2011

How to count all subfolders in an directory?

How can I count how many folders (including subfolders) I have under an specific folder?

  • Use find to select the directories and wc to count them.

    find <directory> -mindepth 1 -type d | wc -l
    
    : Wow, is there an faster solution? ;-) ------------------------------------------------- time find product_images/ -mindepth 1 -type d | wc -l 574292 real 67m34.672s user 0m4.272s sys 0m35.790s -------------------------------------------------
    Dan Carley : That's a big tree. The only way you can speed it up is to work on an index of that structure. But creating and updating the index will be just as slow. And the most common tool for indexing and searching the local FS, `locatedb`, won't allow you to refine your search in the same way as `find`.
    asdmin : yes, with 574292 subdirs and who knows what many files, it's the fastest way to cound the dirs
    From Dan Carley
  • tree -d | grep directories | awk -F' ' '{print $1}'

    Dennis Williamson : I'd use `tail` since there could be a directory called "directories" and there's no need for the -F with the awk: `tree -d|tail -n1|awk '{print $1}'`
    From dyasny

0 comments:

Post a Comment