-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpysed.py
More file actions
75 lines (61 loc) · 1.7 KB
/
Copy pathpysed.py
File metadata and controls
75 lines (61 loc) · 1.7 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
"""Sed-like find and replace using Python."""
from __future__ import annotations
import argparse
import re
import sys
from .cli.types import file_existing, regex
def pysed_hook() -> None:
"""Run a sed-like find and replace on files."""
parser = argparse.ArgumentParser(
description="Sed-like find and replace using Python.",
prog="pysed",
)
parser.add_argument(
"-p",
"--pattern",
required=True,
type=regex,
help="The pattern to search for",
)
parser.add_argument(
"-r",
"--replacement",
required=True,
help="The replacement string",
)
parser.add_argument(
"-i",
"--ignore-case",
action="store_true",
help="Make the search case insensitive",
)
parser.add_argument(
"files",
nargs="+",
type=file_existing,
help="The files to operate on",
)
args = parser.parse_args()
flags = 0
if args.ignore_case:
flags = re.IGNORECASE
if _process_files(args.files, args.pattern, args.replacement, flags):
sys.exit(1)
def _process_files(
files: list[str],
pattern: str,
replacement: str,
flags: int,
) -> bool:
"""Process the list of files and perform the replacement."""
regex = re.compile(pattern, flags=flags)
modified = False
for filepath in files:
with open(filepath, "r", encoding="utf-8") as file:
content = file.read()
new_content = regex.sub(replacement, content)
if new_content != content:
with open(filepath, "w", encoding="utf-8") as file:
file.write(new_content)
modified = True
return modified