Python Grep
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 )
About this entry
You’re currently reading “ Python Grep ,” an entry on Chui's Counterpoint
- Published:
- 1.28.09 / 2pm
- Category:
- General
Comments are closed
Comments are currently closed on this entry.