use warnings;
use strict;
my $matching_line_loc = 0;
my $matching_line = '';
open (TEST_FILE, "<test.dat")
or die "Couldn't open test.dat: $!\n";
while (<TEST_FILE>) {
if (/333/) { #remember matching line and line number
$matching_line = $_;
$matching_line_loc = $.;
last;
}
}
close TEST_FILE;
if ($matching_line) { #don't bother with rest if no match!
open (TEST_FILE, "<test.dat")
or die "Couldn't open test.dat: $!\n";
open (TMP_FILE, ">test.tmp")
or die "Couldn't open/create test.tmp: $!\n";
#print the matching line first
print TMP_FILE $matching_line;
#print everything BUT the matching line
while (<TEST_FILE>) {
print TMP_FILE $_ unless $. == $matching_line_loc;
}
close TMP_FILE;
close TEST_FILE;
#remove original file and rename rearranged file
unlink "test.dat" or die "couldn't remove test.dat: $!\n";
rename "test.tmp", "test.dat";
}
Note that this way (and others above) avoids the classic problem of 'slurping' the whole file into memory since it only deals with single lines at a time. Slurping would be pretty bad with a 60 meg file (though it would probably still work.)
This method also assumes that there will only every be one matching line.
Hanlon's Razor - "Never attribute to malice that which can be adequately explained by stupidity"
|