summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBen Sima <bsima@groq.com>2020-05-08 17:14:35 -0700
committerBen Sima <bsima@groq.com>2020-05-08 17:14:35 -0700
commite0f4ca7d52ff781b4c4ae3adc7da1c323e1f7051 (patch)
treeb3d2930853ac0aa5ca4299ca8ca3cea816ccb4a1
parentc0a31f4a3ffcfdf78efb457a8686b6258fe3ad2f (diff)
Add regex support
Unfortunately because this loops over lines, it can't do regexes with newlines in them. Anyway in that case it's probably worth it to just use sed.
-rwxr-xr-xreplace14
1 files changed, 12 insertions, 2 deletions
diff --git a/replace b/replace
index ebbc4e6..7cfda9d 100755
--- a/replace
+++ b/replace
@@ -5,6 +5,7 @@ replace stuff in a file or files
import argparse
import difflib
import fileinput
+import re
import sys
cli = argparse.ArgumentParser(description=__doc__)
@@ -14,17 +15,26 @@ cli.add_argument(
cli.add_argument(
"-d", "--dry", action="store_true", help="just print what would have happened"
)
+cli.add_argument(
+ "-r", "--regex", action="store_true", help="use regex instead of literal replace"
+)
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",
+ "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=not args.dry):
- replacement = line.replace(args.old, args.new)
+ if args.regex:
+ replacement = re.sub(args.old, args.new, line)
+ else:
+ replacement = line.replace(args.old, args.new)
if (args.verbose or args.dry) and args.old in line:
diff = list(differ.compare([line], [replacement]))
sys.stderr.write(f"{fileinput.filename()}:{fileinput.lineno()}:\n")