"perl -p -i -e" trick in Python?

Jeremy Bowers jerf at jerf.org
Tue Feb 15 21:05:27 EST 2005


On Wed, 16 Feb 2005 15:18:57 +0900, Wonjae Lee wrote:

> I read the comment of
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277753.
> (Title : Find and replace string in all files in a directory)
> 
> "perl -p -i -e 's/change this/..to this/g'" trick looks handy.
> Does Python have a similar trick? Or, is there a shorter Python recipe for
> the given problem?

As a Python lover... I still tend to use "perl -pi -e", except in rare
cases where I either can't deal with or don't want to deal with the
necessary escaping, in which case I write a quick perl script like this
(just did this today):

#!/usr/bin/perl
$source = join "", <>;
$source =~ s/\"\"\".*?\"\"\"[ \n]*//gs;
print $source;

While a Python-golf contest might be able to beat that (although,
truthfully, to match this feature for feature I'd be surprised... that <>
is a substantial whack of code to fully emulate and I use this both as a
pipe and by feeding it a long list of files as arguments), I still
couldn't have written it as quickly.

Upshot is, perl is good for something, and when I'm not doing the job I
have working with perl, I'll still reach for perl -pi -e without shame.
Well, actually, only with the shame that I really need to lookup the
command to save backups and start using it. ("man perlrun"... I know where
to find it, I just need to add it to muscle memory!) Much longer than this
though and I drop the perl and run away, if possible.



More information about the Python-list mailing list