-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmulti-replacer.py
More file actions
executable file
·54 lines (40 loc) · 1.4 KB
/
multi-replacer.py
File metadata and controls
executable file
·54 lines (40 loc) · 1.4 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
#!/usr/bin/env python3
import os
import sys
mappingTable = {}
def do_replace(dirpath, file):
# Read in the file
with open(dirpath + "/" + file, 'r') as inputFile:
filedata = inputFile.read()
# Replace the target string
for key in mappingTable:
if not (filedata.find(key) == -1):
filedata = filedata.replace(key, mappingTable[key])
# Write the file out again
with open(dirpath + "/" + file, 'w') as outputFile:
outputFile.write(filedata)
def main():
if len(sys.argv) < 4:
print(
f"Usage: {sys.argv[0]} FILE_EXTENSION FOLDER MAPPING_FILE OPTIONAL_MAPPING_DELIMITER\n"
f" E.g.: {sys.argv[0]} properties test test/mapping.txt"
)
exit(1)
fileMask = sys.argv[1]
folder = sys.argv[2]
mappingFile = sys.argv[3]
with open(mappingFile) as mappingTableFile:
for line in mappingTableFile:
if line.strip() and not line.startswith('#'):
if len(sys.argv) == 5:
(key, val) = line.split(sys.argv[4])
else:
(key, val) = line.split()
mappingTable[key] = val.replace('\n', '')
# print(mappingTable)
for dirpath, dnames, fnames in os.walk(folder):
for file in fnames:
if file.endswith(fileMask):
do_replace(dirpath, file)
if __name__ == "__main__":
main()