#!/usr/bin/env python import sys, re, os, os.path, fnmatch, codecs from optparse import OptionParser cwd = os.getcwd() numfiles = 0 numlines = 0 numchanges = 0 encoding = "UTF-8" usage = "%prog [options] arg1 arg2" desc = """Walk the current directory, opening *.text files and replacing matches for the regex arg1 with arg2. E.g., %prog '@c\s*phone' '@c telephone'. Unless the option '-m' is used, changes will only be reported and not actually made.""" def main(): parser = OptionParser(usage=usage, description = desc) parser.add_option("-m", "--make_changes", action="store_true", dest="test", help="Actually make changes instead of just reporting them." ) options, (arg1, arg2) = parser.parse_args() walkdir(arg1, arg2, options.test) def walkdir(arg1, arg2, make_changes=False): "%s" % desc global numfiles, numlines, numchanges change_lines = [] regex = re.compile(r'(%s)' % arg1) # print("-"*80) for path, subdirs, names in os.walk(cwd): for name in names: if fnmatch.fnmatch(name, '[!.]*.text'): numfiles += 1 changed = False f = os.path.join(path,name) sf = f[len(cwd)+1:] # use the relative path as the key fo = codecs.open(f, 'r', encoding) lines = fo.readlines() fo.close() for i in range(len(lines)): numlines += 1 m = regex.search(lines[i]) if m: numchanges += 1 r = " '%s' => '%s' in line %s of %s" %(arg1, arg2, i+1, sf) if make_changes: lines[i] = regex.sub(arg2, lines[i]) changed = True else: line = lines[i] change_lines.append("%s:\n %s" % (r, lines[i].strip())) if changed: fo = codecs.open(f, 'w', encoding) fo.writelines(lines) fo.close() if numchanges: if make_changes: v = "Made" w = "" else: v = "Identified" w = "Append '-m' to the command to actually make these changes" print("%s %s changes in %s lines from %s files:" % (v, numchanges, numlines, numfiles)) for l in change_lines: print(l) print(w) else: print("No changes were found") if __name__ == '__main__': main()