Grant McWilliams
  • Food
    • Blog
    • Websites
    • Seattle Food Events
    • Seattle Farmers Markets
  • Travel
    • Travel Blog
    • Travel Photos
    • Travel Links
    • Trip Journals
      • Europe - 2015
      • New Orleans - 2013
      • Central Mexico - 2010
      • Toulouse/Paris - 2009
      • Paris/Lyon - 2008
      • Peru/Ecuador - 2007
      • British Columbia - 2007
      • Central Mexico - 2006
      • Eastern Europe - 2006
      • Washington D.C. - 2006
      • Where's the rest?
  • Technology
    • Gadgets
      • Blog
      • Websites
      • Android
      • Nokia n900
      • SailfishOS
    • Technology
      • Blog
      • Websites
    • Virtualization
      • Virtualization Blog
      • Websites
      • Xen Howtos
      • Xenserver Howtos
      • KVM Howtos
      • VirtualBox Howtos
      • Virtual OS images
      • Xenapi Admin Tools github
    • Programming
      • Blog
      • Bash
      • Python
      • Websites
      • Downloads
    • Transportation
      • Blog
      • Websites
    • Sustainable Tech
      • Blog
      • Websites
  • Photography
    • Blog
    • Portfolio
  • Random
    • Grantianity
      • Basics
      • Grantisms
      • The River of Life
      • Bus Maintainance
      • Believing in Yourself
    • Creative Writing
    • Login/Logout
    • About

Python

grep a file in python

Details
Category: Python
December 28, 2011

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 = patt.search(line) if match: matchline = match.group() 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 file.seek(0) # 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 grep.py from my downloads section.

Search