Skip to content

Commit a7b46a6

Browse files
author
Abhijit Sarkar
committed
Update grep
1 parent b954aa8 commit a7b46a6

1 file changed

Lines changed: 22 additions & 22 deletions

File tree

grep/grep.py

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,52 @@
11
import re
22

3-
import grep_test as gt # type: ignore[import-not-found]
4-
53

64
def grep(pattern: str, flags: str, files: list[str]) -> str:
75
filename = len(files) > 1
86
line_numbers = "-n" in flags
97
name_only = "-l" in flags
108

11-
pattern_txt = __build_pattern(flags).replace("{}", pattern)
9+
pattern_txt = _build_pattern(pattern, flags)
1210
p = re.compile(rf"{pattern_txt}")
13-
result = []
11+
result: list[str] = []
1412

1513
for f in files:
16-
lines = gt.FILE_TEXT[f].splitlines()
17-
for line_num, line in enumerate(lines):
18-
if not re.search(p, line):
19-
continue
20-
if name_only:
21-
result.append(f)
22-
break
23-
temp = []
24-
if filename:
25-
temp.append(f"{f}:")
26-
if line_numbers:
27-
temp.append(f"{line_num + 1}:")
28-
temp.append(line)
29-
result.append("".join(temp))
14+
with open(f, encoding="UTF-8") as file:
15+
line_num = -1
16+
while line := file.readline().rstrip("\n"):
17+
line_num += 1
18+
if not re.search(p, line):
19+
continue
20+
if name_only:
21+
result.append(f)
22+
break
23+
temp = []
24+
if filename:
25+
temp.append(f"{f}:")
26+
if line_numbers:
27+
temp.append(f"{line_num + 1}:")
28+
temp.append(line)
29+
result.append("".join(temp))
3030

3131
return ("\n".join(result) + "\n") if result else ""
3232

3333

34-
def __build_pattern(flags: str) -> str:
34+
def _build_pattern(pattern: str, flags: str) -> str:
3535
case_insensitive = "-i" in flags
3636
invert = "-v" in flags
3737
whole_line = invert or "-x" in flags
3838

39-
xs = []
39+
xs: list[str] = []
4040
if case_insensitive:
4141
xs.append("(?i)")
4242
if whole_line:
4343
xs.append("^")
4444
if invert:
4545
# Negative lookahead.
4646
# https://www.regular-expressions.info/lookaround.html
47-
xs.append("(?:(?!{}).)*")
47+
xs.append(f"(?:(?!{pattern}).)*")
4848
else:
49-
xs.append("(?:{})")
49+
xs.append(f"(?:{pattern})")
5050
if whole_line:
5151
xs.append("$")
5252

0 commit comments

Comments
 (0)