Skip to content

Instantly share code, notes, and snippets.

@derekedelaney
Created January 24, 2018 18:47
Show Gist options
  • Save derekedelaney/2a3c7c6c87c8a0528188d8975a8af911 to your computer and use it in GitHub Desktop.
Save derekedelaney/2a3c7c6c87c8a0528188d8975a8af911 to your computer and use it in GitHub Desktop.
finds and replaces text in a file
#!/usr/bin/env python3
from __future__ import print_function
from contextlib import closing
import os
import sys
import argparse
import fileinput
def text_replace(fileToSearch, textToSearch, textToReplace):
with closing(fileinput.FileInput(fileToSearch, inplace=True, backup='.bak')) as file:
for line in file:
print(line.replace(textToSearch, textToReplace), end='')
return True
def main():
parser = argparse.ArgumentParser()
parser.add_argument("file", help="Name of the file")
parser.add_argument("find_text", help="Text to find in file")
parser.add_argument("replace_text", help="Text to replace the found text")
args = parser.parse_args()
if not text_replace(args.file, args.find_text, args.replace_text):
sys.exit(1)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment