#!/usr/bin/env python #--------------------------------------------------------------------# # The script # # (1) does a recursive search of directories, # # (2) looks for a word in all the files (with a given suffix) and # # (3) replaces it with another word. # #--------------------------------------------------------------------# import re import os import sys import time from optparse import OptionParser from fileinput import input #----------------------------------------- # Function to search and replace in a file #----------------------------------------- def searchReplaceFile(fileName, oldWord, newWord): data = open(fileName).read() open(fileName,"w").write( re.sub(oldWord,newWord,data) ) def process(filename, oldWord, newWord, ext): if os.path.isdir(filename): return processdir(filename, oldWord, newWord, ext) else: if os.path.normcase(filename).endswith(ext): try: searchReplaceFile (filename, oldWord, newWord) except IOError, msg: sys.stderr.write("Can't open: %s\n" % msg) return 1 def processdir(dir, oldWord, newWord, ext): try: names = os.listdir(dir) except os.error, msg: sys.stderr.write("Can't list directory: %s\n" % dir) return 1 files = [] for name in names: fn = os.path.join(dir, name) process(fn, oldWord, newWord, ext) def optparse_parsing(): usage = "Usage: %prog [options] fileSuffix oldWord newWord" parser = OptionParser(usage = usage) parser.add_option('-i', '--confirm', dest='confirm', action='store_true', default=False, help='Confirm each replacement') options, args = parser.parse_args(sys.argv[1:]) if (len(args) < 3): parser.error("Inconrrect number of arguments") return options.confirm, args EXEC_DIR = os.getcwd() print EXEC_DIR confirm, args = optparse_parsing() ext = args[0] oldWord = args[1] newWord = args[2] process(EXEC_DIR, oldWord, newWord, ext)