in reply to Comparing Dates
#!/usr/bin/perl -w use Date::Calc qw(Delta_Days); my $dirname = "."; my (@files, @log_lines); my %months = ( 'Jan' => 1, 'Feb' => 2, 'Mar' => 3, 'Apr' => 4, 'May' => 5, 'Jun' => 6, 'Jul' => 7, 'Aug' => 8, 'Sep' => 9, 'Oct' => 10, 'Nov' => 11, 'Dec' => 12, ); # get the list of text files opendir DIR, "$dirname"; @dircontent = grep { /\.txt$/ } readdir(DIR); closedir DIR; # Compute today's date my @today = (localtime(time))[3..5]; $today[1]++; $today[2] += 1900; # foreach text file, compute lines condition foreach $filename (@dircontent) { open FILE, "<$filename"; while(<FILE>) { my $line = $_; # see if line matches date format if($line =~ /^\[(\w{3}?) (\d{2}?)[^\]]*(\d{4}?)(.*)$/) { # assumed 'one month older' as being over 30 days. # if the line is older than 30 days, save it into an array # and write it later. If not, write it to a temp file (Delta_Days($3, $months{$1}, $2, $today[2], $today[1], $today[0] +) > 30 ) ? push @log_lines, $line : keep_line($line); } else { keep_line($line); } } close FILE; # The following lines restore the initial file but without old lines unlink $filename; rename "temp.tmp", $filename; } # archive old lines open ARCH, ">>archive.arc"; foreach $line (@log_lines) { print ARCH "$line"; } close ARCH; # Just append a line to temp file sub keep_line { my $line = shift; open TEMP, ">>temp.tmp"; print TEMP "$line"; close TEMP; }
|
|---|