[Tutor] Equivalent of grep in python
Alan Gauld
alan.gauld at btinternet.com
Mon Dec 22 01:08:03 CET 2008
"Matt Herzog" <msh at blisses.org> wrote
> I can't help wondering how to do this in python:
>
> perl -wnl -e '/string/ and print;' filename(s)
The first thing to say is that python is not Perl so there will
be things Perl does more easily than Python and vice versa.
(For example Pythons intersactive mode is miles better
than perls "read from stdin" mode) Perl is better than python
for quick n dirty one liners, no question. And for every Perl
one liner there will be a relatively short script that can be
written. But you will probably be as well using Perl for
those - its not a bad thing to know and use more than
one language, quite the opposite.
> Not that I want to forget the precious few bits of Perl I do know,
> but I'd rather be totally reliant on python for such tasks.
Why? I'd hate to be totally reliant on any one language for anything
Whether it be Python, Lisp, C or assembler!
To answer your question I think the answer to your one liner
would look something like:
import fileinput # for iterating over several files
for line in fileinput.input(inplace=1): # files = argv[1:]
try:
line.replace('string', 'edit')
print line
except IOError:
continue # ignore bad filenames
This also should help the OP answer his question about how to
generate filenames, line numbers etc - use fileinput and the
filename(), filelineno() etc functions...
Not as short as Perl but more maintainable.
If you really must do a one liner its probably possible although
it will be longer in Python, but I'm not even going to attempt
it - thats what awk/perl are there for!
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list