| 1 |
#!/bin/env python3 |
| 2 |
|
| 3 |
usageHelp = r""" |
| 4 |
|
| 5 |
Replace a given string with another string in a file (but only touch the file |
| 6 |
if there were changes). |
| 7 |
|
| 8 |
""" |
| 9 |
|
| 10 |
|
| 11 |
def getCmndLineOptions(): |
| 12 |
from argparse import ArgumentParser, RawDescriptionHelpFormatter |
| 13 |
|
| 14 |
clp = ArgumentParser(description=usageHelp, |
| 15 |
formatter_class=RawDescriptionHelpFormatter) |
| 16 |
|
| 17 |
clp.add_argument( |
| 18 |
"-s", dest="stringToReplace", required=True, |
| 19 |
help="String to repalce" ) |
| 20 |
|
| 21 |
clp.add_argument( |
| 22 |
"-r", dest="replacementString", required=True, |
| 23 |
help="Replacement string" ) |
| 24 |
|
| 25 |
clp.add_argument( |
| 26 |
"-f", dest="inputFile", required=True, |
| 27 |
help="Input file (and also output if -o <file> not specified)" ) |
| 28 |
|
| 29 |
clp.add_argument( |
| 30 |
"-o", dest="outputFile", default="", |
| 31 |
help="Output file (optional)" ) |
| 32 |
|
| 33 |
options = clp.parse_args(sys.argv[1:]) |
| 34 |
|
| 35 |
if options.outputFile == "": |
| 36 |
options.outputFile = options.inputFile |
| 37 |
|
| 38 |
return options |
| 39 |
|
| 40 |
|
| 41 |
# |
| 42 |
# Main() |
| 43 |
# |
| 44 |
|
| 45 |
if __name__ == '__main__': |
| 46 |
|
| 47 |
import sys |
| 48 |
|
| 49 |
inOptions = getCmndLineOptions() |
| 50 |
|
| 51 |
with open(inOptions.inputFile, 'r') as file: |
| 52 |
lines = file.readlines() |
| 53 |
|
| 54 |
fileWasChanged = False |
| 55 |
newLines = [] |
| 56 |
for line in lines: |
| 57 |
newLine = line.replace(inOptions.stringToReplace, inOptions.replacementString) |
| 58 |
if newLine != line: |
| 59 |
fileWasChanged = True |
| 60 |
newLines.append(newLine) |
| 61 |
|
| 62 |
if (fileWasChanged or inOptions.outputFile != inOptions.inputFile): |
| 63 |
with open(inOptions.outputFile, 'w') as file: |
| 64 |
file.writelines(newLines) |