Monday, October 11, 2004

Python: Custom Grep Template

Sometimes a normal grep doesn't cut it. A template for a fancier grep written in Python would look like this:

#!/usr/bin/env python
import fileinput, sys
searchterm = sys.argv[1]
sys.argv[1:] = sys.argv[2:]
response = "%s: '%s' found %d times on line %d."
for line in fileinput.input():
    num_matches = line.count(searchterm)
    if num_matches:
        print response % (fileinput.filename(),
            searchterm, num_matches,
            fileinput.filelineno())
        print line
This would be a baseline for something more useful.

0 comments: