-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathglobal_replace.py
executable file
·53 lines (41 loc) · 1.41 KB
/
global_replace.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/usr/bin/env python
#
## Natural Language Toolkit: substitute a pattern with a replacement in every file
#
# Copyright (C) 2001-2014 NLTK Project
# Author: Edward Loper <[email protected]>
# Steven Bird <[email protected]>
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
# NB Should work on all platforms, http://www.python.org/doc/2.5.2/lib/os-file-dir.html
import os, stat, sys
def update(file, pattern, replacement, verbose=False):
if verbose:
print("Updating:", file)
# make sure we can write the file
old_perm = os.stat(file)[0]
if not os.access(file, os.W_OK):
os.chmod(file, old_perm | stat.S_IWRITE)
# write the file
s = open(file, 'rb').read()
t = s.replace(pattern, replacement)
out = open(file, 'wb')
out.write(t)
out.close()
# restore permissions
os.chmod(file, old_perm)
return s != t
if __name__ == '__main__':
if len(sys.argv) != 3:
exit("Usage: %s <pattern> <replacement>" % sys.argv[0])
pattern = sys.argv[1]
replacement = sys.argv[2]
count = 0
for root, dirs, files in os.walk('.'):
if not ('/.git' in root or '/.tox' in root):
for file in files:
path = os.path.join(root, file)
if update(path, pattern, replacement):
print("Updated:", path)
count += 1
print("Updated %d files" % count)