use strict; my $match = 'var2 = 3'; my $in = 'in.txt'; my $tmp = 'temp.txt'; my $ext = 'extract.txt'; my ($inh, $tmph, $exth, $last); open($inh, $in); open($tmph, ">$tmp"); open($exth, ">$ext"); while (<$inh>) { if (index($_, $match) == -1) { print $tmph $last; $last = $_; next; } print $exth $last, $_; $last = ''; print $exth (scalar<$inh>) for (1..9); } close($inh); close($tmph); close($exth); unlink($in); rename($tmp, $in);