Python One-Liners

I find myself wanting to do simple text mangling on the command line a lot. Most recently, I wanted to add up the size of all my hard drives from df -h. So, the other day I decided to pick up my old camel book and learn how to do one-liners in Perl. With Mark's help, I got a working script:
df -h | perl -e '$i=0; while (<>) {$i+=$1 if m/(\d+)G/;} print "$i\n";'
After that, I decided having something like perl -ne for Python would be great. So, here it is:
import fileinput, sys
from re import *
code = sys.argv.pop(1)
_ = fileinput.input()
exec code
I call it pyne. Instead of an implicit loop like Perl has, I use list comprehensions to make it useful. Here's the one-liner (requires Python 2.4+):
df -h | pyne "print sum(int( for m in [search(r'(\d+)G', m) for m in _] if m)"

No comments:

Post a Comment