forked from TriBITSPub/TriBITS
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add string-replace.py (TriBITSPub#429)
Will help in future refactorings. I mostly just added this as a precursor to token-replace.py.
- Loading branch information
1 parent
07aeef0
commit 0cd49ce
Showing
1 changed file
with
64 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
#!/bin/env python3 | ||
|
||
usageHelp = r""" | ||
Replace a given string with another string in a file (but only touch the file | ||
if there were changes). | ||
""" | ||
|
||
|
||
def getCmndLineOptions(): | ||
from argparse import ArgumentParser, RawDescriptionHelpFormatter | ||
|
||
clp = ArgumentParser(description=usageHelp, | ||
formatter_class=RawDescriptionHelpFormatter) | ||
|
||
clp.add_argument( | ||
"-s", dest="stringToReplace", required=True, | ||
help="String to repalce" ) | ||
|
||
clp.add_argument( | ||
"-r", dest="replacementString", required=True, | ||
help="Replacement string" ) | ||
|
||
clp.add_argument( | ||
"-f", dest="inputFile", required=True, | ||
help="Input file (and also output if -o <file> not specified)" ) | ||
|
||
clp.add_argument( | ||
"-o", dest="outputFile", default="", | ||
help="Input file (and also output if -o <file> not specified)" ) | ||
|
||
options = clp.parse_args(sys.argv[1:]) | ||
|
||
if options.outputFile == "": | ||
options.outputFile = options.inputFile | ||
|
||
return options | ||
|
||
|
||
# | ||
# Main() | ||
# | ||
|
||
if __name__ == '__main__': | ||
|
||
import sys | ||
|
||
inOptions = getCmndLineOptions() | ||
|
||
with open(inOptions.inputFile, 'r') as file: | ||
lines = file.readlines() | ||
|
||
fileWasChanged = False | ||
newLines = [] | ||
for line in lines: | ||
newLine = line.replace(inOptions.stringToReplace, inOptions.replacementString) | ||
if newLine != line: | ||
fileWasChanged = True | ||
newLines.append(newLine) | ||
|
||
if (fileWasChanged or inOptions.outputFile != inOptions.inputFile): | ||
with open(inOptions.outputFile, 'w') as file: | ||
file.writelines(newLines) |