2019-04-19 01:49:44 +00:00
|
|
|
import argparse
|
2016-11-18 06:24:52 +00:00
|
|
|
import codecs
|
2019-04-19 01:49:44 +00:00
|
|
|
import glob
|
2016-11-18 06:24:52 +00:00
|
|
|
import sys
|
2019-04-19 01:49:44 +00:00
|
|
|
|
|
|
|
def contentreplace(filename, replace_from, replace_to, autoyes=False):
|
2019-03-22 21:51:02 +00:00
|
|
|
f = open(filename, 'r', encoding='utf-8')
|
|
|
|
with f:
|
|
|
|
content = f.read()
|
2016-11-18 06:24:52 +00:00
|
|
|
|
2019-03-22 21:51:02 +00:00
|
|
|
occurances = content.count(replace_from)
|
2019-04-19 01:49:44 +00:00
|
|
|
|
|
|
|
print(f'{filename}: Found {occurances} occurences.')
|
2019-03-22 21:51:02 +00:00
|
|
|
if occurances == 0:
|
|
|
|
return
|
2016-11-18 06:24:52 +00:00
|
|
|
|
2019-04-19 01:49:44 +00:00
|
|
|
permission = autoyes or (input('Replace? ').lower() in ('y', 'yes'))
|
|
|
|
if not permission:
|
|
|
|
return
|
2016-11-18 06:24:52 +00:00
|
|
|
|
2019-03-22 21:51:02 +00:00
|
|
|
content = content.replace(replace_from, replace_to)
|
2016-11-18 06:24:52 +00:00
|
|
|
|
2019-03-22 21:51:02 +00:00
|
|
|
f = open(filename, 'w', encoding='utf-8')
|
|
|
|
with f:
|
|
|
|
f.write(content)
|
|
|
|
|
2019-04-19 01:49:44 +00:00
|
|
|
def contentreplace_argparse(args):
|
|
|
|
filenames = glob.glob(args.filename_glob)
|
|
|
|
for filename in filenames:
|
|
|
|
contentreplace(
|
|
|
|
filename,
|
|
|
|
codecs.decode(args.replace_from, 'unicode_escape'),
|
|
|
|
codecs.decode(args.replace_to, 'unicode_escape'),
|
|
|
|
autoyes=args.autoyes,
|
|
|
|
)
|
|
|
|
|
|
|
|
def main(argv):
|
|
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
|
|
|
|
|
|
parser.add_argument('filename_glob')
|
|
|
|
parser.add_argument('replace_from')
|
|
|
|
parser.add_argument('replace_to')
|
|
|
|
parser.add_argument('-y', '--yes', dest='autoyes', action='store_true', help='accept results without confirming')
|
|
|
|
parser.set_defaults(func=contentreplace_argparse)
|
|
|
|
|
|
|
|
args = parser.parse_args(argv)
|
|
|
|
args.func(args)
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
raise SystemExit(main(sys.argv[1:]))
|