traverse directory and count the number of files

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • briggs
    New Member
    • Dec 2009
    • 5

    #1

    traverse directory and count the number of files

    Hi All,

    I need to take the count of txt and bak files present in all the directory.for eg if we assume there are two directoies say(test1, test2), I need to collect the count(of txt and bak files) and print it out..

    I tried the below code, but could not achieve what I need.Can someone help me on the same.

    Prg:
    Code:
    ($dir, $extension) = @ARGV;
       $dir = "." unless $dir;
       $lextension = "txt" unless $lextension;
       $dirCount = 0;
       &loopDir($dir);
       #$dirCount=$dircount-1;
       print "Number of directories = $dirCount";
       
       exit;
    
    sub loopDir {
       local($dir, $margin) = @_;
       chdir($dir) || die "Cannot chdir to $dir\n";
       $dirCount++;
       local(*DIR);
       $filelCount=0;
       $filetCount=0;
       opendir(DIR, ".");
       while ($f=readdir(DIR)) {
          next if ($f eq "." || $f eq "..");
          
          if (-d $f) {
             &loopDir($f,$margin."   ");
          }elsif ($f=~/\.$lextension$/) {
             print "$dir\n";
             $filelCount++;
             print "Number of files with .$lextension = $filelCount\n";
      }
           if ($f=~/\.bak$/) {
            $filetCount++;
            print "Number of files with .bak = $filetCount\n";
          }
        
       }#while
       closedir(DIR);
       chdir("..");
    }
    Expected outcome:

    C:\Users\ram\my contents\test>p erl count.pl
    Number of directories = 2
    Test1
    Number of files with .txt = 1
    Number of files with .bak = 1
    Test2
    Number of files with .txt = 1
    Number of files with .bak = 2
    Last edited by numberwhun; Dec 15 '09, 06:41 PM. Reason: Please use code tags!
  • RonB
    Recognized Expert Contributor
    • Jun 2009
    • 589

    #2
    Start by adding this near the top of the script.
    Code:
    use strict;
    use warnings;
    Those pragmas will point out lots of problems. To begin with, you'll need to declare each of your vars with the my keyword.

    It would be better to use the File::Find or File::Find::Rul e module.



    That's assuming your instructor will let you use the module.

    Comment

    Working...