Skip to content

Instantly share code, notes, and snippets.

@hdf
Created August 9, 2014 19:17
Show Gist options
  • Save hdf/c934e01b3cc785901e40 to your computer and use it in GitHub Desktop.
Save hdf/c934e01b3cc785901e40 to your computer and use it in GitHub Desktop.
incremental regex replace in python
import os, sys, re
pattern = re.compile("<ID>\d+<\/ID>", re.I | re.M)
file = 'EoCApp.CT'
if len(sys.argv) > 1:
file = sys.argv[1]
f = open(file, 'r')
s = f.read()
f.close()
i = -1
def r(l):
global i
i += 1
return '<ID>' + str(i) + '</ID>'
s = pattern.sub(r, s)
l = file.rfind('.')
file2 = file[:l] + '2.' + file[l+1:]
f = open(file2, 'w')
f.write(s)
f.close()
print file2 + " written."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment