If you need to know how to do the replacement on the string, look at perlre. You could do s/pattern/string/s; but if so, as your pattern match will span multiple lines, you will need the whole file as a single string, which can use up memory on big files.

The alternative is the suggestion by the other poster - run through each line and use a flag to tell you whether you are in a replaceable section.

The more awkward problem is how to replace the text in the file. Again, it is perfectly valid to just open an INPUT filehandle and an OUTPUT filehandle, then to rename the new file to overwrite the old one. However, that is quite complex. A neater idea might be to write a shell script and use some of perl's command line switches. (See perlrun for details.) Something like:

find . -name *.ext -print | xargs perl -pi.bk -e \ ' if ($flag && /end_match/) {$flag = 0;} if ($flag) { $sub = $printed++? '': 'My text to substitute'; s/^.*$/$sub/; } if (/start_match/) {$flag++;$printed = 0;} '
That's untested but you get the general idea. Find finds and prints the relevant files. xargs takes the filename and passes it to the end of the perl command. perl reads the filename, prints a copy to filename.bk (you can remove the .bk once you are sure your pattern works), and alters the original file.

No good if you're on windows though...

dave hj~


In reply to Re: Modifying A Bunch of Files by replacing specific lines by dash2
in thread Modifying A Bunch of Files by replacing specific lines by ishaqali

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.