#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2010
    Posts
    3
    Rep Power
    0

    How to count directories in Unix script?


    I am learning shell scripting and I created the script below to count directories but it puts the list in memory and I have too many directories so I run out of memory with the error "There is not enough memory available now." Does anybody has suggestions on how to do this somehow else? Maybe write the list of directories to a file? Help me please!

    Code:
    #!/bin/sh
    START=$1
    DIRS=$(find "$START" -type d)
    for d in $DIRS
    do
          CNT=$(print "$(ls -l $d | grep dr | wc -l)" | nawk '{gsub(/^[ ]*/,"",$0); gsub(/[ ]*$/,"",$0)
          if [ "$CNT" != 0 ]; then
             echo "$d dirctory has "$CNT" directories" >> dircount.log
          fi
    done
    Thanks,
    Zepogi
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2007
    Posts
    168
    Rep Power
    7
    Code:
    find . -type d -exec ksh -c 'printf "%1s has %1s directories\n" $1 $(find $1/* -type d -prune -ls 2>/dev/null | wc -l)"' dircnt {} \;
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2010
    Posts
    3
    Rep Power
    0
    Thank you! It worked perfect and way more easier than what I was trying to do - Thanks again!

    zepogi

IMN logo majestic logo threadwatch logo seochat tools logo