Skip to content

Instantly share code, notes, and snippets.

@RDCH106
Last active February 3, 2022 05:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save RDCH106/057e82b4fb2a94de6306cc00997d5d8f to your computer and use it in GitHub Desktop.
Save RDCH106/057e82b4fb2a94de6306cc00997d5d8f to your computer and use it in GitHub Desktop.
Searching and Replacing Text in a File
#!/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