BV45
BV45

Reputation: 605

Need to loop through directory and all of it's subdirectories to find files at a certain in Perl

I am attempting to loop through a directory and all of its sub-directories to see if the files within those directories are a certain size. But I am not sure if the files in the @files array still contains the file size so I can compare the size( i.e. - size <= value_size ). Can someone offer any guidance?

use strict;
use warnings;
use File::Find;
use DateTime;

my @files;
my $dt   = DateTime->now;  
my $date = $dt->ymd;
my $start_dir = "/apps/trinidad/archive/in/$date";


my $empty_file = 417;
find( \&wanted, $start_dir);
for my $file( @files )
{
  if(`ls -ltr | awk '{print $5}'`<= $empty_file)
  {
        print "The file $file appears to be empty please check within the    folder if this is empty"


  }
  else
  return;

}
exit;

sub wanted {
 push @files, $File::Find::name unless -d;
 return; 
} 

Upvotes: 0

Views: 92

Answers (1)

Chris Charley
Chris Charley

Reputation: 6633

I think you could use this code instead of shelling out to awk.

(Don't understand why my empty_file = 417; is an empty file size).

if (-s $file <= $empty_file)

Also notice that you are missing an open and close brace for your else branch.

(Unsure why you want to 'return' if the first file found that is not 'empty' branches to the return which doesn't do anything because return is only used to return from a function).

The exit is unnecessary and the return in the wanted function is unnessary.

Update: A File::Find::Rule solution could be used. Here is a small program that captures all files less than 14 bytes in my current directory and all of it's subdirectories.

#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use File::Find::Rule;

my $dir = '.';
my @files = find( file => size => "<14", in => $dir);
say -s $_, " $_" for @files;

Upvotes: 2

Related Questions