Repository navigation
Expand file tree
/
Copy pathrecursive_replace.py
More file actions
57 lines (40 loc) · 1.68 KB
/
Copy pathrecursive_replace.py
File metadata and controls
57 lines (40 loc) · 1.68 KB
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
54
55
56
#!/usr/bin/env python
"""
RecursiveReplace
~~~~~~~~~~~~~~~~
Performs a recursive directory replace for a simple string
"""
import os
import sys
def main():
if len(sys.argv) < 4:
sys.exit('Insufficient command line arguments')
find = sys.argv[1]
replace = sys.argv[2]
extension = sys.argv[3]
recursiveReplace = RecursiveReplace()
count = recursiveReplace.replace(find, replace, os.getcwd(), extension)
print str(count) + " occurences replaced"
class RecursiveReplace():
ignoredDirectories = ['vendor']
def replace(self, find, replace, rootDirectory, extension):
totalReplacements = 0
for directory, directories, files in os.walk(rootDirectory):
""" Ignore any directories in the ignoredDirectories variable """
if any(ignoredDirectory not in directory for ignoredDirectory in self.ignoredDirectories):
for fileName in files:
if fileName.endswith('.' + extension):
filePath = os.path.join(directory, fileName)
with open(filePath) as f:
s = f.read()
matches = s.count(find)
if matches > 0:
print str(matches) +" occurences found in " + filePath
s = s.replace(find, replace)
totalReplacements += matches
with open(filePath, "w") as f:
f.write(s)
return totalReplacements
# Execute script
if __name__ == '__main__':
main()