Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

perl - Creating a script to delete old log files, that allows me to pass directory/age/regex arguments

I'm trying to create a PERL script to delete old log files. One of the key things I want the script to be able to do is allow me to pass arguments for directory, name of the file (such as test.log-*), and age of the file.

It's been a while since I've used PERL and I'm not that great anyway, so I'd appreciate some help. I'm also not terribly familiar with the getopt::long module. Here's what I'm thinking so far, and while I'm sure it's not correct, please give me any feedback that might assist.

I want to run the script along the lines of "script.pl --dir /release/logs --type test.log-* --days 7"

#!/usr/perl

use strict;
use warnings;
use Data::Dumper;
use Getopt::Long;

my $file;
my ($dir,$type,$days);
GetOptions( 'dir'   => $dir,
            'type'  => $type,
            'days'  => $days);

foreach my $file (<$dir/$type>){
   if (-M $file < $days) {
       print "
 Deleting log more than '$days' old:".$file;
       unlink $file;
       # or die "
 Failed to remove $file";
   }
}

exit;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you insist on using Perl, look into File::Find & friends. Though if you're on a *nix box you should probably be aware of find(1) for tasks this common.

try: find /release/logs -name test.log-* -mtime +7 -delete

If you want to test it out 1st, leave off the -delete flag & it will just print a list of the files it would have otherwise deleted.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...