Skip to content

Instantly share code, notes, and snippets.

@highfestiva
Last active November 3, 2023 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save highfestiva/4a992e7ca28fc861fa0e7b7fc8b0ea2b to your computer and use it in GitHub Desktop.
Save highfestiva/4a992e7ca28fc861fa0e7b7fc8b0ea2b to your computer and use it in GitHub Desktop.
Replace file contents while traversing all subdirectories
#!/bin/env python
def printUsage():
import sys
print("%s <regexp-search> <regexp-replace> <wildcard>" % sys.argv[0])
print("Example: %s \"<td>[0-9]*</td>\\r\\n\" 0 *.html" % sys.argv[0])
def doreplace(r, search, replace):
orig = r.read();
import re
prev = '?????!?!?!?!?!'
data = orig
while data != prev:
prev = data
data = re.sub(search, replace, data, flags=re.MULTILINE);
if data != orig:
return data
def main():
import sys
args = sys.argv;
if len(args) != 4:
printUsage();
sys.exit(1)
import glob, os
search, replace, wildcard = args[1:4]
fls = glob.glob(wildcard, recursive=True)
for fn in fls:
outfn = fn+".tmp"
try:
with open(fn, "rt") as r:
outdata = doreplace(r, search, replace)
if outdata:
with open(outfn, "wt") as w:
w.write(outdata);
os.remove(fn)
os.rename(outfn, fn)
print("Replaced in " + fn)
except Exception as ex:
try:
os.remove(outfn)
except:
pass
print("Could not replace in", fn, "reason:", type(ex), ex)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment