Gossamer Forum
Home : General : Perl Programming :

Delete all Empty Files

Quote Reply
Delete all Empty Files
Hiya,

I would like to be able to search through a directory, and delete all empty files in that directory. I don't want to look through the perl documentation, because I am tired. If anybody has any code handy, or knows where I can get some to do this trick, it would be much appreciated.

Thank you.
account deleted
Quote Reply
Re: [andy_C] Delete all Empty Files In reply to
Code:
my $dir = "/path/to/dir";

opendir (DIR, $dir) or die $!;
@files = grep { !/^\./ } readdir(DIR);
closedir(DIR);
Code:
foreach (@files) {
-z "$dir/$_" and unlink("$dir/$_");
}

Last edited by:

PaulWilson: Sep 16, 2001, 3:12 PM
Quote Reply
Re: [PaulWilson] Delete all Empty Files In reply to
Wow Paul - excellent code. Thanks!
account deleted
Quote Reply
Re: [andy_C] Delete all Empty Files In reply to
No worries.

Heres a slightly different version to tell you what was deleted and it allows you to pass in the directory path..:

Code:
#!/usr/bin/perl

use CGI qw(:standard);

print header;

my $dir = param('dir') || "/apache/apache/cgi-bin/dev";
my $pass = param('pass');

$pass eq "MY_SECRET_WORD" or &error("No no no");

$dir =~ /^[\w.-]+$/ or &error("Invalid directory");

opendir (DIR, $dir) or &error("Error : $!");
@files = grep { !/^\./ } readdir(DIR);
closedir(DIR);

foreach (@files) {
-z "$dir/$_" and unlink("$dir/$_"), print "rm : $dir/$_<br>";
}


sub error {
print $_[0];
exit;
}



You'd do script.cgi?pass=MY_SECRET_WORD&dir=/path/to/dir



Last edited by:

PaulWilson: Sep 16, 2001, 4:58 PM
Quote Reply
Re: [PaulWilson] Delete all Empty Files In reply to
Thanks Paul. You're up really late! Don't you have uni tomorrow? Sorry, I forgot, you're a student. So you don't go to uni. Lol.
account deleted
Quote Reply
Re: [andy_C] Delete all Empty Files In reply to
Still on summer holidays :)

Go back next week.
Quote Reply
Re: [andy_C] Delete all Empty Files In reply to
I think I picked that up somewhere. I apologise if you're a middle aged Brazilian coffee-picker. Which I doubt you are.
account deleted
Quote Reply
Re: [andy_C] Delete all Empty Files In reply to
Hehe.....I altered the code above incase you didn't notice to use a password as otherwise it isn't secure.

Anyway still use with caution on a public server.

Last edited by:

PaulWilson: Sep 16, 2001, 4:59 PM
Quote Reply
Re: [PaulWilson] Delete all Empty Files In reply to
Thanks Paul. It's really useful, and I learnt a new trick too Cool
account deleted
Quote Reply
Re: [andy_C] Delete all Empty Files In reply to
What trick is that? :)

Woops.....you may want to chage

$dir =~ /^[\w.-]+$/ or &error("Invalid directory");


to

$dir =~ /^[\w.-\/]+$/ or &error("Invalid directory");

Blush

Last edited by:

PaulWilson: Sep 17, 2001, 2:09 PM