This is a test file. Here comes the line we want: 'syslogd') You see it? It was two lines ago. And before this line we want to output the other stuff. #### This is a test file. Here comes the line we want: 'syslogd') You see it? It was two lines ago. 'bgs') /usr/bin/su - patrol /usr/adm/best1_default/bgs/scripts/best1collect -q>>\$LOG 2>>\$LOG ;; And before this line we want to output the other stuff. #### ($line =~ m/'syslogd'\)/); #### my $newline = $. + 3; #### $newline = $bgs; print OUT $newline; next; #### 'bgs') /usr/bin/su - patrol /usr/adm/best1_default/bgs/scripts/best1collect -q>>\$LOG 2>>\$LOG ;; #### #!/usr/bin/perl -w use strict; my $bgs = <<'HERE'; 'bgs') /usr/bin/su - patrol /usr/adm/best1_default/bgs/scripts/best1collect -q>>$LOG 2>>$LOG ;; HERE # Read the whole file into memory. This makes things easier # for us. Later we can use Tie::File to treat the file # as an array. my @lines = ; my $saw_bgs; for my $line (@lines) { if ($line =~ /bgs/) { $saw_bgs++; print "I saw 'bgs' in line >$line<\n"; }; }; if (! $saw_bgs) { print "I did not see 'bgs' at all.\n"; }; open my $out, ">", 'test.out' or die "Couldn't create 'test.out': $!"; # Output our file, adding $bgs if necessary my $print_bgs; # Counter for when to print $bgs for my $line (@lines) { if ($line =~ /'syslogd'\)/) { $print_bgs = 2; # Three lines to go } elsif (defined $print_bgs and $print_bgs > 0) { $print_bgs--; # another line done } elsif (defined $print_bgs and $print_bgs == 0) { print {$out} $bgs; # Yay, we counted three lines, so now we can output $bgs } else { # Nothing to do, just a normal line }; print {$out} $line; }; __DATA__ This is a test file. Here comes the line we want: 'syslogd') You see it? It was two lines ago. And before this line we want to output the other stuff.