my $modified_text = ""; my $counter = 0; my $db_line = ""; my $text; open (FH, "<", "some_file"); while () { if (m/^\s*DATABASE: /i) { # This will only match if 'DATABASE:' appears on the start of the line, or is prefixed with whitespace. /i since the case of the word probably doesn't matter. if (defined $db_line) { my $insert = "WIDGETS FOUND: $counter\n"; # The text to insert right after the 'database:'-line. $modified_data .= $db_line . $insert . $text; } $counter = 0; $text = ""; $db_line = $_; next; } # When should the counter be increased? if (m/WIDGET/) { $counter++: } $text .= $_; } close (FH); open (FH, ">", "some_file"); print FH $modified_text; if (defined $db_line) { my $insert = "WIDGETS FOUND: $counter\n"; # The text to insert right after the last 'database:'-line. print FH $db_line . $insert . $text; } close (FH);