# ==============================================================================
"""REPLACE : replace all occurrences of a string in a set of text files"""
# ==============================================================================
__author__  = "Christophe Schlick"
__version__ = "2.0" # process an arbitrary set of files
__date__    = "2015-09-01"
__usage__   = """
User input : <oldstring> <newstring> <filename> [filename...]
App output : modify all 'filename' by replacing each 'oldstring' by 'newstring'
Note: use quotes if 'oldstring' or 'newstring' contains space characters"""
# ==============================================================================
from ezCLI import *
# ------------------------------------------------------------------------------
def replace(oldstring:str, newstring:str, name:str) -> str:
  """replace each occurrence of 'oldstr' by 'newstr' in file 'name'"""
  text = read_txt(name) # read whole content of file 'name'
  count = text.count(oldstring)
  text = text.replace(oldstring, newstring)
  write_txt(name, text)
  return "%s : %s strings have been replaced" % (name, count)
# ------------------------------------------------------------------------------
def parser(command:str) -> str:
  """extract arguments from 'command' before calling 'replace()'"""
  oldstring, newstring, *names = parse(command); inspect()
  return '\n'.join(replace(oldstring, newstring, name) for name in names)
# ==============================================================================
if __name__ == '__main__':
  userloop(parser, "Enter <oldstr> <newstr> <name> [name...]")
# ==============================================================================
