Python Grep
Wednesday, 28 January 2009
From ZazzyBob
Occasionally I have to wade through log files on sites running Windows, since our program is python based, it’s useful to be able to have these tools on hand without downloading exes. I’m hosting a copy here just in case it gets lost in the interweb.
#!/usr/bin/python
#< PYTHON - simple grep through a file - supports regex
# Usage: grep.py "pattern" file
# Written to test my fledgling python knowledge!
import sys
import re
arguments = sys.argv
def print_usage():
print "USAGE:"
print "grep.py \"pattern\" filename"
if len(arguments) != 3:
print_usage()
sys.exit(1)
searchterm = arguments[1]
file = arguments[2]
print "Searching for %s in %s" % ( searchterm, file )
try:
fileToSearch = open( file, 'r' )
except IOError:
print "No such file"
sys.exit(2)
# Well, we've got this far - the file must exist!
data = fileToSearch.read()
data = data.split('\n')
patternprog = re.compile( searchterm )
for line in data:
a_match = patternprog.search( line )
if ( a_match ):
print line
fileToSearch.close()
sys.exit( 0 )
You should follow me on twitter here
No. 1 — January 29th, 2009 at 5:40 pm
[...] Python Grep | Chui’s counterpoint [...]