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

Hello all, Ive had great success editing files with perl based off knowing a set position in the file. Looking for help with editing a file based off some key words. I need to be able to open a file that changes size, search for
# *** END NEW MAPPING RULES SECTION ***
Once this line is found, I need to be able to write to the file one line above the search field. Appreciate the help!

Replies are listed 'Best First'.
Re: Help editing a file based off seach criteria
by Corion (Patriarch) on Jan 12, 2009 at 17:15 UTC

    When manipulating text files, one approach would be to use Tie::File. Another approach would be to rewrite the file yourself by using $^I.

    Without seeing what code you already have, it's somewhat hard to suggest the best approach. So help us to help you, by providing the code you already have and telling us where you have encountered problems.

      Here is how I find the string in the file:
      #!/usr/bin/perl open DATA, "</home/file.conf"; my @list = grep /\END\b/, <DATA>; chomp @list; print "$_\n" foreach @list;
      How do I take the starting position, of the file where END is found (only will occur one time), and move up one position to write to the file?

        You could use a loop instead of using grep, and keep a counter to remember the line number, or just remember not only the current line but also the line before it.

        my @list = <DATA>; chomp @list; my $prev_line; for my $line (@list) { # Look at current line # remember this line as "previous" };
Re: Help editing a file based off seach criteria
by apl (Monsignor) on Jan 12, 2009 at 19:52 UTC
    Don't worry about how to do it in Perl. Ask yourself "If I was doing this by hand, how would I accomplish the task?".

    Once you see the logic laid out, you'll be able to write the equivalent code.