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

Hi,

Please advice How can I retrieve and replace text in one Perl line. I retrieve "napre" & "jupiter" strings from GPPRegistry file (As describe below), and want in the same Perl line to replace those texts in the file to "Text1" & Text2":

perl -ne "print if /\bnapre/i || /\bjupiter/i" GPPRegistry.temp.reg

I wrote some sketch, but currently it's doesn't "work":

perl -ne "print if /\bnapre/i || /\bjupiter/i;" -ne "s/napre/Text1/gi +;" GPPRegistry

Please adviec.

Thanks.

20071119 Janitored by Corion: Removed font tags, colors, added formatting, code tags, as per Writeup Formatting Tips

Replies are listed 'Best First'.
Re: Retrieve & Replace strings in one Perl line.
by moritz (Cardinal) on Nov 12, 2007 at 20:26 UTC
    perl -ne 's/napre/Text1/gi; print if /\bnapre/i || /\bjupiter/i;' GPPRegistry
      I'm not sure from the way the question is worded but, since it is a registry file the requirement might be just to change those lines with "jupiter" and "napre" (are they hostnames?) leaving other lines in the file untouched. -pe might be more appropriate.

      perl -pi.bak -e "s/\bnapre/Text1/gi; s/\bjupiter/Text2/gi;" GPPRegistr +y

      Just a guess.

      Cheers,

      JohnGG

      The output of the command is:
      perl -ne "print if /\\bnapre/i || /\\bjupiter/i;" GPPRegistry.temp.reg
      "DBLogin"="napre"
      "DSN"="jupiter"
      "DBLogin"="napre"
      "Login"="napre"
      "Password"="napre"
      "DBLogin"="napre"
       
      I want in the same command to replace "napre" with "TEST1" and present it (Not change the file yet).
      after this command the fields include "napre" are despaired and the replacement of "napre" weren't be shown
       
      perl -ne 's/napre/Text1/gi; print if /\bnapre/i || /\bjupiter/i;' GPPRegistry.temp.reg
      "DSN"="jupiter"
      "DSN"="jupiter"
Re: Retrieve & Replace strings in one Perl line.
by tuxz0r (Pilgrim) on Nov 12, 2007 at 20:50 UTC
    Are you wanting to modify the file "inplace"? If so, you can use the -i option to have perl write the changes to the file. If you give -i an optional extension (e.g. -i.bak) then it will save the original file with that extension before applying any changes (always a good idea).

    ---
    echo S 1 [ Y V U | perl -ane 'print reverse map { $_ = chr(ord($_)-1) } @F;'
    Warning: Any code posted by tuxz0r is untested, unless otherwise stated, and is used at your own risk.