Grep Equivalent for Python

sjdevnull at yahoo.com sjdevnull at yahoo.com
Thu Mar 15 02:20:20 EDT 2007


Alex Martelli wrote:
> tereglow <tom.rectenwald at eglow.net> wrote:
>    ...
> > server using the /proc FS.  For example, in order to obtain the amount
> > of physical memory on the server, I would do the following in shell:
> >
> > grep ^MemTotal /proc/meminfo | awk '{print $2}'
>
> If you would indeed do that, maybe it's also worth learning something
> more about the capabilities of your "existing" tools, since
>
>   awk '/^MemTotal/ {print $2}' /proc/meminfo
>
> is a more compact and faster way to perform exactly the same task.


That's correct on small files, but note that at least on my platform
(Linux, GNU grep and awk), "grep" is just massively insanely faster
than awk (to the point where doing the equivalent on /usr/share/dict/
words takes 10-20% of the time with "grep re|awk..." as it does with
"awk '/re...'"

On this small proc file, the plain-awk version is faster (and it's
cleaner looking), as Alex points out.

But for large files, "grep" is often _way_ faster than awk/perl/python/
whatever alternative, easily swamping the fork/exec cost.  It's often
quite handy to keep that in mind.




More information about the Python-list mailing list