Grep in Python 2
May 28, 2018
Here's some quick example code I used to perform a grep in Python 2.
:::python import os, fnmatch, ConfigParser, time
def locate(pattern, root=os.curdir): """ Locate all files matching supplied filename pattern in and below the supplied root directory """ for path, dirs, files in os.walk(os.path.abspath(root)): for filename in fnmatch.filter(files, pattern): yield os.path.join(path, filename) lTransactionCounts = {} for lEachFile in locate('*.java', root='/folder/'): print ".", for line in open(lEachFile): if ".txnGet" in line: lStart = line.find(".txnGet") + 1 lEnd = line.find("(", lStart) if lEnd == -1: lEnd = line.find(" ", lStart) if lEnd == -1: lEnd = len(line) lTransaction = line[lStart:lEnd] print lTransaction, try: lCount = lTransactionCounts[lTransaction] except KeyError: lCount = 0 lCount += 1 lTransactionCounts[lTransaction] = lCount for result in lTransactionCounts.keys(): print "%s %s" % (result, lTransactionCounts[result])