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

J

Jeremy Bowers

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.
 
J

Jack Diederich

sure.

python -c 'import os; os.system("sed -i s/change this/...tothis/g")'

You beat me to it, but you can cut a few more characters out of that.

/tmp/> python
Python 2.3.4 (#2, Jan 5 2005, 08:24:51)
Type "help", "copyright", "credits" or "license" for more information./tmp/> sed -i 's/change this/...tothis/g'


-Jack
 
C

Christos TZOTZIOY Georgiou

/tmp/> python
Python 2.3.4 (#2, Jan 5 2005, 08:24:51)
Type "help", "copyright", "credits" or "license" for more information.

"Instant porting of any program to python". Smooth.
 
B

Bart van Deenen

Jack Diederich said:
/tmp/> python
Python 2.3.4 (#2, Jan 5 2005, 08:24:51)
Type "help", "copyright", "credits" or "license" for more information.


:) :) :) :) :) :) :) :) :) :) :) :) :)

Bart
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top