From 52087d5bcad3ab7ca34ca0292c89b3f8c622cce1 Mon Sep 17 00:00:00 2001 From: Ben Sima Date: Mon, 17 May 2021 08:06:00 -0400 Subject: add raw regex and fix bug --- replace | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/replace b/replace index 7cfda9d..a622d8f 100755 --- a/replace +++ b/replace @@ -1,7 +1,8 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 """ replace stuff in a file or files """ +# maybe i should just use https://replace.richardlloyd.org.uk/ import argparse import difflib import fileinput @@ -30,12 +31,21 @@ args = cli.parse_args() differ = difflib.Differ() + +def raw(s): + return r"{}".format(s) + + +def log(s): + sys.stderr.write(s) + + for line in fileinput.input(files=args.files, inplace=not args.dry): if args.regex: - replacement = re.sub(args.old, args.new, line) + replacement = re.sub(raw(args.old), args.new, line, flags=re.MULTILINE) else: replacement = line.replace(args.old, args.new) - if (args.verbose or args.dry) and args.old in line: + if (args.verbose or args.dry) and (line != replacement): diff = list(differ.compare([line], [replacement])) sys.stderr.write(f"{fileinput.filename()}:{fileinput.lineno()}:\n") sys.stderr.writelines(diff) -- cgit v1.2.3