import os import sys import re import getopt import commands import subprocess import fnmatch import fileinput MATCH_FILE = "" TARGET_STRING = "" REPLACE_STRING = "" class color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m' def showusage(): print color.BOLD + "Usage:" + color.END print "python %s -m \'match_file\' -t \'target_string\' -r \'replace_string\'" % sys.argv[0] def getparamater(argv): try: opts, args = getopt.getopt(argv, "m:t:r:", ['match=target=replace=']) return opts, args except getopt.GetoptError: showusage() sys.exit(1) def isparamatervalid(): if len(MATCH_FILE) > 0 and len(TARGET_STRING) > 0 and len(REPLACE_STRING) > 0: return True return False def replace_match_filename_string(match_filename, oldstring, newstring): status, files = commands.getstatusoutput('find . -type f -name \'' + match_filename + '\'') for file in files.splitlines(): replace_file_string(file, oldstring, newstring) def replace_file_string(filepath, oldstring, newstring): for line in fileinput.input(filepath, inplace = 1): sys.stdout.write(line.replace(oldstring, newstring)) if __name__ == "__main__": opts, args = getparamater(sys.argv[1:]) for opt, arg in opts: if opt in ("-m", "--match"): MATCH_FILE = arg if opt in ("-t", "--target"): TARGET_STRING = arg if opt in ("-r", "--replace"): REPLACE_STRING = arg if isparamatervalid(): replace_match_filename_string(MATCH_FILE, TARGET_STRING, REPLACE_STRING) else: showusage() sys.exit(1)