Shell Script To Count Number Of Files In Each Subdirectories

Posted on in Categories Decision Making, File-management last updated September 19, 2008

13 comment

  1. 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.

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

  3. 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

  4. 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

  5. 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

  6. 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.

Leave a Comment