Created
November 14, 2016 19:26
-
-
Save digi9ten/abfc01ffe63f9dd01ebc49bcfe21622e to your computer and use it in GitHub Desktop.
When doing a search and replace of strings that contain '/', ie: URLs, sed and or printf make not always work. Use this.
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
import argparse | |
# | |
# Long story short, using sed/printf does always handle strings that contain '/' them (e.g.: urls) | |
# | |
parser = argparse.ArgumentParser() | |
parser.add_argument('fileToSearch', type=file) | |
parser.add_argument('textToSearch', type=str) | |
parser.add_argument('textToReplace', type=str) | |
args = parser.parse_args() | |
with open(args.fileToSearch.name, 'r') as file: | |
filedata = file.read() | |
filedata = filedata.replace(args.textToSearch, args.textToReplace) | |
with open(args.fileToSearch.name, 'w') as file: | |
file.write(filedata) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Initially, based on a stackoverflow answer, I used the fileinput(?) lib, but heard a number of corrections stating that the above solution is better, unless you're dealing with a large file.