Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Perl script to delete *.pdf files older then 2 days in subfolders 1

Status
Not open for further replies.

TheTechGuy

Technical User
Jun 19, 2004
3
CA
Hi there,

I have the following script which deletes all the *.pdf files in one folder older then 2 days, but I need something which would delete all the *.pdf files in all the sub-folders

#!/usr/bin/perl
STDERR

$dir = "c:/test/pdf" ;

opendir (DIR, "$dir/");
@FILES = grep(/.pdf/,readdir(DIR));
closedir (DIR);

foreach $FILES (@FILES) {
if (-M "$dir/$FILES" > 2) {
unlink("$dir/$FILES");
}
}
 
Have a look at the File::Find module, if you still want to do it using readdir you can't depend on grep to pattern match the pdfs, because you're going to have to push the other directories on to the stack, and iterate over the stack until empty.

HTH
--Paul


It's important in life to always strike a happy medium, so if you see someone with a crystal ball, and a smile on their face ...
 
run recursiv (programm it). something like:

....
opendir()
while(this-file = readdir()){
if(its-a-dir(this-file)){
next if(this-file eq "."));
next if(this-file eq ".."));
system("$0 this-file");
next;
}
next if(not-a-pdf-file(this-file));
next if(younger-as-N-days(this-file));
unlink(this-file);
}


:) guggach
 
if there is only 1 level of nested directories this will loop through them - you just need to add the code to delete the file if older than 2 days. it will ignore all files that don't end with .PDF

Code:
#!/usr/bin/perl

$main_dir = "/Users/duncancarr/Desktop/PDF_files copy";

opendir (DIR, "$main_dir");
@directories = grep(/^[^.]/,readdir(DIR));
closedir (DIR);

foreach $nested_dir (@directories) {
  print "$nested_dir\n";
  print "—" x length($nested_dir);
  print "\n";
  opendir (DIR, "$main_dir/$nested_dir");
  @files = grep(/.pdf/,readdir(DIR));
  closedir (DIR);
  print join "\n", @files;
  print "\n\n";
}


Kind Regards
Duncan
 
Using File::Find::Rule makes this a simple task:
Code:
#!/usr/bin/perl -w
use strict;
use File::Find::Rule;

my $dir = '/home/username/test';

for (File::Find::Rule->file->in($dir)) {
   unlink $_ if (-M $_ > 2);
}
 
if this is on *nix:

find /path_to_dir -type f -iname '*\.pdf' -mtime +2 -exec rm {} \;

This will remove *.pdf & *.PDF
if there symlink subdirs, add
-follow
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top