use warnings; use strict; my $matching_line_loc = 0; my $matching_line = ''; open (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.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 () { 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"; }