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

Probably a really lame newbie-question. I'm trying to replace some text in some txt-files with a perl call like this...

perl -pi -e "s/brad(.+?)bill/brian$1bob/gm;" *.txt

This should replace "brad123bill" by "brian123bob" - but instead I just get "brianbob". What's wrong? Probably something with the $1 variable, but what?

Regards
Martin
  • Comment on Replacing text - problem with $1 variable

Replies are listed 'Best First'.
Re: Replacing text - problem with $1 variable
by matsmats (Monk) on Sep 03, 2003 at 09:52 UTC

    Try either:

    perl -pi -e 's/brad(.+?)bill/brian$1bob/gm;' *.txt

    or

    perl -pi -e "s/brad(.+?)bill/brian\$1bob/gm;" *.txt

    Seems like $1 is interpolated before your code is run.

    Mats

      Woohoo! It works when changing " to '. Thanks! :)

      What I'm trying to do is replacing some code in some php-files from $_GET["whatever"] to get("whatever) and $_POST["whatever"] to post("whatever") so I can make some functions that handles all http-arguments with special characters like æøåöü by converting them to html-tags like ø

      Martin
        perl -pi -e 's/\$_(GET|POST)\[([^\]]*)]/lc($1) . "($2)"/egm;' test.php
        Assuming there's no nested square brackets inside your argument list to $_GET[] and $_POST[], that will work.
Re: Replacing text - problem with $1 variable
by broquaint (Abbot) on Sep 03, 2003 at 09:44 UTC
    Seems to work here. Update: which is obvious since I'm using single quotes (non-interpolative) and you're using double-quotes (interpolative) so the $1 is being interpolated and the replace part of s/// actually looks like brianbob. Try something like this (i.e using single-quotes) and your code should work fine
    perl -le '$_="brad123bill"; print; s/brad(.+?)bill/brian$1bob/; print' brad123bill brian123bob

    HTH

    _________
    broquaint

Re: Replacing text - problem with $1 variable
by jeffa (Bishop) on Sep 03, 2003 at 13:36 UTC
    Looks like the problem is solved, but if you are wanting to grab digits into $1, why not grab digits instead?
    s/brad(\d+)bill/brian$1bob/gm
    Also, i am still bummed out by the long-standing fact that this:
    perl -le'$foo="bar";print $foo'
    only works for *NIX, while this:
    perl -le"$foo='bar';print $foo"
    only works for Win32 ... it's not Perl's fault, which makes me think that we will never have naturally portable one-liners. :(

    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)