Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi, i m a starter in perl. Below is a stupid way of describing the problem but still i wrote it. hope u guys wont mind it. How can I search a text file and match 2 lines of text and insert 5 lines after it ?
file : basic.txt The text to be searched : I got the idea but I dont have money 5 lines to be added: yes thats correct but your should have money with you otherwise it is not possible
I hope somebody helps me in solving this problem ? seems like difficult task to me.

Replies are listed 'Best First'.
Re: matching multiple line
by derby (Abbot) on Mar 11, 2002 at 15:39 UTC
    AM,

    perldoc -f perlfaq5 for adding lines and perldoc -f perlfaq6 for matching across lines

    -derby

Re: matching multiple line
by fuzzyping (Chaplain) on Mar 11, 2002 at 20:15 UTC
    Here's a simple script that will do what you're asking. Rather than editing the existing file, it redirects to a new file "text.out". If you need to, simply add a system command to rename text.out to basic.txt. Obviously, there are better/different ways of handling this, but you weren't very specific about your scenario.

    -fuzzyping
    #!/usr/bin/perl use strict; my $string_to_match = "I dont have money"; my $string_to_insert = "yes thats correct\nbut your should have\nmoney + with you\notherwise it is not\npossible\n"; open(INFILE, "basic.txt"); open(OUTFILE, ">>text.out"); while (<INFILE>) { unless (/$string_to_match/) { print OUTFILE $_; } else { print OUTFILE $_, $string_to_insert; } } close(OUTFILE); close(INFILE); 1;