Last active
February 3, 2022 05:52
-
-
Save RDCH106/057e82b4fb2a94de6306cc00997d5d8f to your computer and use it in GitHub Desktop.
Searching and Replacing Text in a File
This file contains hidden or 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 python | |
import os | |
import sys | |
nargs = len(sys.argv) | |
if not nargs == 5: | |
print("usage: %s search_text replace_text infile outfile" % os.path.basename(sys.argv[0])) | |
elif sys.argv[3] == sys.argv[4]: | |
print("infile and outfile must be different") | |
else: | |
stext = sys.argv[1].replace("\\n", "\n") | |
rtext = sys.argv[2].replace("\\n", "\n") | |
input = sys.stdin | |
output = sys.stdout | |
if nargs > 3: | |
input = open(sys.argv[3]) | |
if nargs > 4: | |
output = open(sys.argv[4], 'w') | |
for s in input.readlines(): | |
output.write(s.replace(stext, rtext)) | |
output.close() | |
input.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment