in reply to Re: Search and replace next line
in thread Search and replace next line

So it has to search for a line, replace 0 in the following line with a 1 and save that in the file.

You replace one line in a file by rewriting the whole file( at least that is the easiest way). So you can use one of the two snippets above (I believe both work, but there seems to be dissent, so check first) to read your .ini file and write the results to a new file. Check if it is good and then copy it over the original .ini file.

If you feel confident in the script you can also automatically have Perl overwrite the input file with the -i switch.

perl -i rep.pl config.ini

Replies are listed 'Best First'.
Re^3: Search and replace next line
by perlnewbie2000 (Initiate) on Jan 05, 2005 at 12:07 UTC
    I'm having some trouble getting it to work.
    Will you look at my code and see what could be wrong?

    $cs="d:\\Perl\\Compiler_Setup.ini"; open cs or die "Cannot open $cs for read :$!"; while (<cs>) { if (m/"Gimpel PC-Lint for H8]"/){ # read the line to be replaced my $line = <cs>; # do something with it $line =~ s/1/0/; # print the new version print $line; } }

    Right now it just doesn't do anything.
    in a command prompt I write
    perl "replace test.pl"
    and then it just goes back to d:\perl> as if it ran the program, and then just goes back to where I was before. It says:

    D:\Perl>perl "replace test.pl"

    D:\Perl>
      You seem to have trouble opening the file. Perl can do this for you. Try this:
      while (<>) { print; if (m/Gimpel PC-Lint for H8\]/){ # read the line to be replaced my $line = <>; # do something with it $line =~ s/1/0/; # print the new version print $line; } }
      and run it as "perl replace_test.pl Compiler_Setup.ini". If the output looks okay, use "perl -i replace_test.pl Compiler_Setup.ini"
        So instead of opening the file like I do: perl "replace test.pl" then write: perl "replace test.pl Compiler_Setup.ini" and then it will open the file Compiler_setup so that I can read lines out of it? NICE :D
        and if I set the -i attrib it will change the line LocalCompilerPresent=0 in Compiler_Setup.ini to =1 ??

        Sorry for asking this many questions, I just want to know that I got it right :) I'm quite new to perl, but I think it's fun.. :)