-
Notifications
You must be signed in to change notification settings - Fork 0
/
replace.py
32 lines (21 loc) · 1.01 KB
/
replace.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#!/usr/bin/python3
###
# By MarcelFox
# Usage: python3 replace.py -h
###
import sys, argparse, shutil, fileinput
def replace():
parser = argparse.ArgumentParser(description="Replace a string in a text file and save it.")
parser.add_argument("text_file", metavar="FILE", action="store", type=str, help="Path of the file to be used.")
parser.add_argument("-o", "--output", metavar="", action="store", type=str, help="Path of the output of the new file.")
parser.add_argument("-p", "--pattern", metavar="", action="store", type=str, help="Pattern that you want to change.")
parser.add_argument("-s", "--string", metavar="", action="store", type=str, help="The string that will replace the pattern.")
args = parser.parse_args()
if args.output:
shutil.copyfile(args.text_file, args.output)
else:
args.output = args.text_file
for line in fileinput.input(args.output, inplace=True):
line = line.replace(args.pattern, args.string)
sys.stdout.write(line)
replace()