Skip to content

Commit

Permalink
Add string-replace.py (TriBITSPub#429)
Browse files Browse the repository at this point in the history
Will help in future refactorings.  I mostly just added this as a precursor to
token-replace.py.
  • Loading branch information
bartlettroscoe committed Dec 14, 2022
1 parent 07aeef0 commit 0cd49ce
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions refactoring/string-replace.py
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)

0 comments on commit 0cd49ce

Please sign in to comment.