By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,834 Members | 2,234 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,834 IT Pros & Developers. It's quick & easy.

traverse directory and count the number of files

P: 5
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:
Expand|Select|Wrap|Line Numbers
  1. ($dir, $extension) = @ARGV;
  2.    $dir = "." unless $dir;
  3.    $lextension = "txt" unless $lextension;
  4.    $dirCount = 0;
  5.    &loopDir($dir);
  6.    #$dirCount=$dircount-1;
  7.    print "Number of directories = $dirCount";
  8.  
  9.    exit;
  10.  
  11. sub loopDir {
  12.    local($dir, $margin) = @_;
  13.    chdir($dir) || die "Cannot chdir to $dir\n";
  14.    $dirCount++;
  15.    local(*DIR);
  16.    $filelCount=0;
  17.    $filetCount=0;
  18.    opendir(DIR, ".");
  19.    while ($f=readdir(DIR)) {
  20.       next if ($f eq "." || $f eq "..");
  21.  
  22.       if (-d $f) {
  23.          &loopDir($f,$margin."   ");
  24.       }elsif ($f=~/\.$lextension$/) {
  25.          print "$dir\n";
  26.          $filelCount++;
  27.          print "Number of files with .$lextension = $filelCount\n";
  28.   }
  29.        if ($f=~/\.bak$/) {
  30.         $filetCount++;
  31.         print "Number of files with .bak = $filetCount\n";
  32.       }
  33.  
  34.    }#while
  35.    closedir(DIR);
  36.    chdir("..");
  37. }
  38.  
Expected outcome:

C:\Users\ram\mycontents\test>perl 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
Dec 12 '09 #1
Share this Question
Share on Google+
1 Reply


Expert Mod 100+
P: 589
Start by adding this near the top of the script.
Expand|Select|Wrap|Line Numbers
  1. use strict;
  2. 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::Rule module.
http://search.cpan.org/~dapm/perl-5....b/File/Find.pm
http://search.cpan.org/~rclamp/File-...e/Find/Rule.pm

That's assuming your instructor will let you use the module.
Dec 12 '09 #2

Post your reply

Sign in to post your reply or Sign up for a free account.