counting number of directories in a specific directory

后端 未结 15 2227
被撕碎了的回忆
被撕碎了的回忆 2020-12-22 21:06

How to count the number of folders in a specific directory. I am using the following command, but it always provides an extra one.

find /directory/ -maxdept         


        
15条回答
  •  别那么骄傲
    2020-12-22 21:25

    The best answer to what you want is

    echo `find . -maxdepth 1 -type d | wc -l`-1 | bc
    

    this subtracts one to remove the unwanted '.' directory that find lists (as patel deven mentioned above).

    If you want to count subfolders recursively, then just leave off the maxdepth option, so

    echo `find . -type d | wc -l`-1 | bc
    

    PS If you find command substitution ugly, subtracting one can be done as a pure stream using sed and bc.

    Subtracting one from count:

    find . -maxdepth 1 -type d | wc -l | sed 's/$/-1\n/' | bc
    

    or, adding count to minus one:

    find . -maxdepth 1 -type d | wc -l | sed 's/^/-1+/' | bc
    

提交回复
热议问题