Skip to content

Instantly share code, notes, and snippets.

@digi9ten
Created November 14, 2016 19:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save digi9ten/abfc01ffe63f9dd01ebc49bcfe21622e to your computer and use it in GitHub Desktop.
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.
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)
@digi9ten
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment