Skip to content

Instantly share code, notes, and snippets.

@smartm13
Last active March 15, 2019 17:35
Show Gist options
  • Save smartm13/f17480377b35826dad032507b82b6bb5 to your computer and use it in GitHub Desktop.
Save smartm13/f17480377b35826dad032507b82b6bb5 to your computer and use it in GitHub Desktop.
Batch string find replace #untested
#batch find replace
basepath=input("Enter fullpath of project rootdir:")
findtext=input("Enter fullpath of find_to text file:")
reptext=input("Enter fullpath of replace_with text file:")
endswithfilter=input("Enter the string the target files should end with [.html for example]:")
#setting
progress=1000#report after every n no. of files.
encoding='latin-1'#encoding to read and write all files with
valid,_i=[0,0],0
print("Reading find_to and replace_with files.")
with open(findtext,encoding=encoding) as f:find_to=f.read()
with open(reptext,encoding=encoding) as f:replace_with=f.read()
print("Starting Job:")
for root,dirs,files in __import__("os").walk(basepath):
for file in files:
if not _i%progress:print('Processed {} files.'.format(_i))
_i+=1
if file.endswith(endswithfilter):
target=__import__("os").path.join(root,file)
with open(target,encoding=encoding) as f:src=f.read()
c=src.count(find_to)
valid=[valid[0]+c,valid[1]+int(bool(c))]
dest=src.replace(find_to,replace_with)
with open(target,'w',encoding=encoding) as f:f.write(dest)
print("Job completed.")
if not sum(valid):print("No find_to text found in files with this filter. [Check path/filter]")
else:print("Total {} replacements in total {} files".format(*valid))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment