Grant McWilliams

Tech Programming Python


grep a file in python

Grep in Linux is an amazing tool. Sometimes I just want the simplicity of grep in Python. This isn't the equal to grep but it will take a regular expression as an argument (two examples shown) and give a return code of success if found or None if not. It will also return the line just like grep. 


#!/usr/bin/env python
import re

def grep(patt,file):
    """ finds patt in file - patt is a compiled regex
        returns all lines that match patt """
    matchlines = []
filetxt = open(file) lines = filetxt.readlines() for line in lines: match = if match: matchline = matchlines.append(matchline) results = '\n '.join(matchlines) if results: return results else: return None # Example use textfile = "/etc/hosts" file = open(textfile) criteria = "localhost" expr = re.compile(r'.*%s.*' % criteria) # finds line that starts with anything, ends with anything and has criteria in it #expr = re.compile(r'[0-9].*filename:(%s)\schecksum:.*result: (.*)' % criteria) # more complex example # using return code if grep(expr, file): print criteria + " is in " + textfile else: print criteria + " is not in " + textfile # rewind file for next test # printing all matching lines results = grep(expr, file) print results file.close()

Since Python is so picky about indention (drives me crazy) you can download from my downloads section.

Add a comment