#!/usr/bin/perl use warnings; use strict; open my $FH, '<', 'test.cfg' or die $!; my $pos; while (<$FH>) { $pos = $. if /echo.*install_list$/; # Remember the line number. } die "Pattern not found.\n" unless $pos; $. = 0; # Reset the line number. seek $FH, 0, 0; # Start reading from the beginning again. open my $OUT, '>', 'test.cfg.new' or die $!; while (<$FH>) { print {$OUT} $_; print {$OUT} "test\n" if $. == $pos; # After the remembered line, print the extra text. } close $OUT; rename 'test.cfg.new', 'test.cfg';