Created
January 24, 2018 18:47
-
-
Save derekedelaney/2a3c7c6c87c8a0528188d8975a8af911 to your computer and use it in GitHub Desktop.
finds and replaces text in a file
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
#!/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