≡ Menu

Shell Script To Count Number Of Files In Each Subdirectories

{ 13 comments… add one }
  • Dularl March 9, 2012, 11:53 am

    Hi!

    I learnt a lot from this, but i have a question. I would like to count the file types in each subfolder. For example Directory1 has 4 pdf 3 txt files Directory2 has 1 png 1jpg files.
    And i would like to do this without using awk.

  • crzydg January 4, 2012, 2:57 pm

    Hmmm… getting greater and greater – find the error :-)
    crzydg@aitne ~ $ find -type f -execdir pwd \; | uniq -c |wc -l
    2812
    crzydg@aitne ~ $ find . -type f -printf ‘%h\n’ | sort | uniq -c |wc -l
    2588
    crzydg@aitne ~ $ find . -type f | uniq -c |wc -l
    36394
    crzydg@aitne ~ $ pwd
    /home/crzydg

  • Stephan December 1, 2011, 2:29 pm

    easier:
    find . -name .\* | wc -l
    (counts directories too)

    maybe better:
    find . -name .\* | grep -v “\.\$” | wc -l

  • Vivek November 2, 2011, 3:15 pm

    Here is the Full Script
    #!/bin/bash
    DIRLIST=$(find “$1” -type d)
    for d in $DIRLIST
    do
    [ $d != “.” -a $d != “..” ] && count=$(find “$d” -maxdepth 1 -type f | wc -l)
    printf “Directory name :$d $count \n”
    done

  • suresh August 19, 2010, 12:25 pm

    Greate man…
    superb post.. find command is very versatile…

  • Arnoques July 3, 2010, 6:35 pm

    I like Gagan’s version, but is slow because it executes pwd (an external program) for each file. A faster version:

    find . -type f -printf '%h\n' | sort | uniq -c

    and, to sort by the number of files and only get the first ten you can add

    find . -type f -printf '%h\n' | sort | uniq -c | sort -nr | head

  • Magnus February 12, 2010, 11:33 pm

    Big thanks! I’ve really been looking for this, most helpful!

  • Daniel Iversen July 9, 2009, 11:09 am

    Hi there..

    Love the script, just what I was looking for… Must admit that what someone posted ‘ find -type f -execdir pwd \; | sort | uniq -c ‘ was easier but would not even have found that if it was not for your site.

    Thanks,
    Daniel

  • Ashish Barot March 5, 2009, 6:04 pm

    Hi Gagan,

    can you pl. explain the string which you had paste here.
    what is use case of “f” in your string?

    Regards,
    Ashish Barot.

    • Anonymous December 8, 2011, 4:06 pm

      hi ashish f is here specifying that it should count only files not a directory.

  • Gagan October 16, 2008, 12:32 am

    Even easier-

    find -type f -execdir pwd \; | sort | uniq -c

    • Alex September 16, 2010, 2:44 pm

      You don’t need to sort here. This will work fine too
      find -type f -execdir pwd \; | uniq -c

  • ghostdog74 September 20, 2008, 1:08 pm

    GNU find/awk

    find /path -printf "%h:%f\n" | awk -F: '{d[$1]++}END{ for(o in d) print d[o],o }'

Security: Are you a robot or human?

Leave a Comment