Friday, October 27, 2006
8:05 AM

Search, Process, Replace strings in a File using Perl

I wanted some one-line loop to read a log file containing serial numbers line-by-line, search for a serial using some regular expression, read it into a variable and then mark it as used back into the file so its not used again next time. Here is how it goes

So the file looks something like this

EVAL=SomeSerial1 #Created on Fri Oct 13 11:12:09 2006.
COM=SomeSerial2 #Created on Tue Oct 17 11:19:45 2006.
COM=SomeSerial3 #Created on Tue Oct 17 11:19:45 2006.

#Main
print &getSerialfromFile("./serialnumbers.txt", "COM=");

sub getSerialfromFile($$)
{
my $line;
my ($serials_file, $pattern) = (@_);
open(MAP, $serials_file) or die "failed to open $serials_file, $!";
my @lines = < MAP >
close(MAP);
foreach $line (@lines)
{
next unless ($line =~ s/^$pattern(.*?)\s/used$pattern$1/g) ;
# You can use the serial $1 here
}
open(MAP, ">", "./changed.txt");
print MAP @lines;
close(MAP);
}

0 comments:

Post a Comment