in reply to Modified Date, file renaming
tachyon#!/usr/bin/perl -w <--- this does nothing on win 32 use strict; use warnings; use diagnostics; require 5.6.0; # use / as the path delimiter perl will change it to \ for you # if you use \ you will regret it as this is the escape char # thus c:\thisdir is seen by perl as c:[tab]hisdir as \t is tab my $path = 'c:/logfiles/'; my $file; print "Processing...\n"; opendir(DIR,$path) or die "Unable to open dir $path: $!\n"; my @everything = readdir DIR; closedir DIR; foreach $file(@everything) { next if -d "$path$file"; # skip the directories next unless $file =~ m/\.log$/i; # look for files that end in .log print "Loading $path$file\n"; # if you get to here you have a logfile so slurp it up my @file = &get_file("$path$file",1); # now have lines of file in @ file so iterate through them LINE: for my $line(@file) { # look for whatever you are looking for # call the do stuff sub if you find a foobar if ($line =~ m/foobar/) { &do_stuff(@file); last LINE; # exit from this loop on $file } } } print "Done!\n"; exit; sub do_stuff { my @file = @_; #do you stuff to $file here (the file is in @file if you want it) print "Doing stuff to $path$file\n"; return; } # this sub makes a unique filename by adding numerals to the end of th +e passed # path/filename until it finds one that does not exist or dies after 1 +01 tries # useage: $my_unique_name = &make_unique_filename($filename); sub make_unique_filename { my $filename = shift; no warnings; while (-e $filename) { $filename =~ s/^(.*?)(\d*)$/$1.eval(($2||0)+1)/e; die "Unable to make unique file $filename(0..100) after 101 trie +s!\n" if $2 > 100; } return $filename; } # this sub inputs the script spceified by $path, and unless the $no_ba +ckup # argument is set to true it writes and verifies a backup # useage: @file = &get_file($part,$no_backup); sub get_file { # get arguments my $path = shift; my $no_backup = shift; # get script to process open (FILE, "<", "$path") or die "Unable to open file $path $!\n"; my @file = <FILE>; close FILE; # we will write a backup unless this has been specifically outlawe +d unless ($no_backup) { # make a uniquely named backup file $backup_file = "$path.bak"; $backup_file = &make_unique_filename($backup_file) if -e $back +up_file; # write script to script.bak before proceeding open (FILE, ">", $backup_file) or die "Unable to write backup +file $backup_file $!\n"; for (@file) { print FILE $_; } close FILE; # varify backup is a perfect copy, rampant paranoia is OK beca +use ..it happens open (BACKUP, "<", $backup_file) or die "Backup file failure, +aborting! $!\n"; my @backup = <BACKUP>; close BACKUP; for my $i (0..$#backup) { die "Backup file corrupt, aborting!\n" unless $file[$i] eq + $backup[$i]; } print "Backup of original script written to $backup_file\n"; } return @file; # if all has proceeded as expected we return the scrip +t }
|
|---|