CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Need a Custom or Prewritten Perl Program?: I need a program that...:
delete files in directory if there are more than 3 files.

 



amituts
New User

Mar 30, 2010, 8:09 AM

Post #1 of 2 (4227 views)
delete files in directory if there are more than 3 files. Can't Post

Hi!
I need a script which delete files in a directory when there are more than 3 files exist in that directory. It should delete oldest file and 3 latest file should be remains in that directory.

file format : read_story_12_03_2010.zip
read_story_13_03_2010.zip

Thanks in advance for ur help.


roolic
User

Apr 2, 2010, 2:37 AM

Post #2 of 2 (4180 views)
Re: [amituts] delete files in directory if there are more than 3 files. [In reply to] Can't Post


Code
#!/usr/bin/perl 
use strict;
my ($folder, $max_files) = @ARGV;

die "invalid folder $folder" unless -d $folder;
$folder =~ s/\/$//; # removing / at the end
$max_files ||= 3; # default is 3 files

opendir DIR, $folder || die "can't read folder $folder";
my @files = sort {(stat $folder.'/'.$a)[9] <=> (stat $folder.'/'.$b)[9] }
grep { $_ !~ /^\./ && -f $folder.'/'.$_ } readdir DIR;
closedir DIR;

my $deleted = 0;
while (scalar @files > $max_files ){
my $file = shift @files;
$deleted++ if( unlink $folder.'/'.$file );
}


usage: ./script_name folder

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives