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

Hi!

Im not a perl programmer, but am partial to a specific command line invocation, which I think is fairly well known, namely, in my "letter directory" where I keep my love letter files I do a:
perl -p -i -e 's!oldgirlfriendname!newgirlfriendname!g' *
Yes, fairly self-explanatory and ruthless, I should think.

HOWEVER, the directory has a bunch of other letters which have nothing to do with my girlfriends. However, the above command line, actually changes the modification date on those too, even if no text has been replaced.

Does anybody know a version of this command line invocation where the files not affected by the replacement retain their original modification date?

Thanks in adv.

Replies are listed 'Best First'.
•Re: perlpie only on files with affected contents
by merlyn (Sage) on Apr 29, 2004 at 16:37 UTC
    My usual trick for that is:
    #!/usr/bin/perl $^I = ".bak"; @ARGV = glob "*"; while (<>) { s/old/new/ and $changes = 1; print; if (eof) { # retreat if no changes: rename "$ARGV$^I", $ARGV unless $changes; $changes = 0; # reset } }

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

      Thanks for really fast replies! Much appreciated. I take note of the caveat too.
Re: perlpie only on files with affected contents
by Plankton (Vicar) on Apr 29, 2004 at 16:31 UTC
    $ perl -p -i -e 's!oldgirlfriendname!newgirlfriendname!g' `grep -l old +girlfriend *`

    Plankton: 1% Evil, 99% Hot Gas.
Re: perlpie only on files with affected contents
by EdwardG (Vicar) on Apr 29, 2004 at 16:39 UTC
    grep -il amanda * | xargs perl -p -i.bak -e "s!amanda!barbie!ig"
Re: perlpie only on files with affected contents
by halley (Prior) on Apr 29, 2004 at 16:36 UTC
    Wow, I hope newgirlfriend never finds out your technique. Making a new relationship comfortable is not exactly like copying your favorite .bashrc to a new computer account.

    --
    [ e d @ h a l l e y . c c ]

Re: perlpie only on files with affected contents
by graff (Chancellor) on Apr 29, 2004 at 21:59 UTC
    Do be careful with the string matches... the solutions above involving the "grep" utility will get you into trouble if the old girlfriend is "Jane" and a random set of your files happen to contain the name "Janet"...

    The same concern could apply to the string substitutions that you do: you should perhaps be careful to set it up like so:

    s!\boldgirlfriendname\b!newgirlfriendname!g
    (and heaven help you if you ditch a girl with a name like April, May or June... ;)