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

Hi, I have to modify a generated file. I want to search for a piece of code and after finding it, I have to insert a few more lines after it. file.txt before :
example::func1(xop*){ int n ; printf("hello buddy..\n"); } file.txt after: example::func1(xop*){ int n; printf("hello buddy..\n"); char *point = new char[10]; printf("complete..\n"); }
so basically I wish to add the couple of lines after finding the line printf("hello buddy..\n"); in the text file 'file.txt'

Replies are listed 'Best First'.
(jeffa) Re: inserting few lines after matching a string?
by jeffa (Bishop) on Mar 04, 2002 at 14:10 UTC
    Fun with one-liners:
    perl -pi -e 's/(printf\("hello buddy..\\n"\);\s+)/$1char \*point = new + char\[10\];\n/' file.txt

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
Re: inserting few lines after matching a string?
by Juerd (Abbot) on Mar 04, 2002 at 14:02 UTC

    And your question is...?
    open (IN, 'file.txt'); open (OUT, '>output.txt'); while (<IN>) { print OUT $_; if (/^printf\("hello boddy...."\);\s*$/) { print OUT qq{char *point = new char[10];\n}; print OUT qq{printf("complete..\n");\n}; } } close OUT; close IN;

    #!/usr/bin/perl -i -p # perl foo.pl file.txt if (/^printf\("hello boddy...."\);\s*$/) { $_ .= qq{char *point = new char[10];\n} . qq{printf("complete..\n");\n}; }

    ++ vs lbh qrpbqrq guvf hfvat n ge va Crey :)
    Nabgure bar vs lbh qvq fb jvgubhg ernqvat n znahny svefg.
    -- vs lbh hfrq OFQ pnrfne ;)
        - Whreq
    

Re: inserting few lines after matching a string?
by Spudnuts (Pilgrim) on Mar 04, 2002 at 16:06 UTC
    perldoc -q insert has the answer you sought.
Re: inserting few lines after matching a string?
by joealba (Hermit) on Mar 04, 2002 at 14:20 UTC
    ++!

    If I ever decided to code in C again, I'd probably write a Perl program to generate the code too!

    </sarcasm>