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
|
#!/usr/bin/env python
"""
replace stuff in a file or files
"""
import argparse
import difflib
import fileinput
import sys
cli = argparse.ArgumentParser(description=__doc__)
cli.add_argument(
"-d", "--diff", action="store_true", help="print diffs for every replacement"
)
cli.add_argument("old", type=str, help="target string")
cli.add_argument("new", type=str, help="replacement string")
cli.add_argument(
"files", nargs="*", metavar="FILE", help="file(s) to operate on, or omit for stdin",
)
args = cli.parse_args()
differ = difflib.Differ()
for line in fileinput.input(files=args.files, inplace=True):
replacement = line.replace(args.old, args.new)
if args.diff and args.old in line:
diff = list(differ.compare([line], [replacement]))
sys.stderr.write(f"{fileinput.filename()}:{fileinput.lineno()}:\n")
sys.stderr.writelines(diff)
print(replacement, end="")
|