| 1 | 1 | def grep(pattern: str, flags: str, files: list[str]) -> str: |
| 2 | | pass |
| 2 | # Parse flags |
| 3 | line_numbers = '-n' in flags |
| 4 | filenames_only = '-l' in flags |
| 5 | case_insensitive = '-i' in flags |
| 6 | invert_match = '-v' in flags |
| 7 | exact_match = '-x' in flags |
| 8 | |
| 9 | # Prepare pattern for comparison |
| 10 | search_pattern = pattern.lower() if case_insensitive else pattern |
| 11 | |
| 12 | # Results storage |
| 13 | results = [] |
| 14 | matched_files = set() if filenames_only else None |
| 15 | |
| 16 | # Process each file |
| 17 | for filename in files: |
| 18 | try: |
| 19 | with open(filename, 'r', encoding='utf-8') as file: |
| 20 | # Process each line (memory efficient - line by line) |
| 21 | line_num = 0 |
| 22 | for line in file: |
| 23 | line_num += 1 |
| 24 | # Prepare line for comparison |
| 25 | compare_line = line.lower() if case_insensitive else line |
| 26 | |
| 27 | # Determine if line matches |
| 28 | if exact_match: |
| 29 | # For exact match, compare pattern with line without newline |
| 30 | matches = search_pattern == compare_line.rstrip('\n\r') |
| 31 | else: |
| 32 | matches = search_pattern in compare_line |
| 33 | |
| 34 | # Apply invert flag |
| 35 | if invert_match: |
| 36 | matches = not matches |
| 37 | |
| 38 | # If line matches criteria |
| 39 | if matches: |
| 40 | # Edge Case: When only filenames are requested, collect filenames with matches |
| 41 | if filenames_only: |
| 42 | matched_files.add(filename) |
| 43 | break # No need to check more lines in this file |
| 44 | else: |
| 45 | # Build output line |
| 46 | output_line = "" |
| 47 | # Edge Case: When multiple files, prepend filename |
| 48 | if len(files) > 1: |
| 49 | output_line += f"{filename}:" |
| 50 | # Edge Case: When line numbers flag is set, prepend line number |
| 51 | if line_numbers: |
| 52 | output_line += f"{line_num}:" |
| 53 | output_line += line |
| 54 | results.append(output_line) |
| 55 | except IOError: |
| 56 | # If a file cannot be opened, we skip it according to typical grep behavior |
| 57 | # In a real implementation, grep would output an error message to stderr |
| 58 | continue |
| 59 | |
| 60 | # Edge Case: When only filenames are requested, return them |
| 61 | if filenames_only: |
| 62 | return "\n".join(sorted(matched_files)) + ("\n" if matched_files else "") |
| 63 | |
| 64 | # Edge Case: Handle empty results |
| 65 | if not results: |
| 66 | return "" |
| 67 | |
| 68 | # Join results with newlines |
| 69 | return "".join(results) |
| 70 | |
| 71 | # Handled Edge Cases: files that cannot be read, when only filenames are requested, when multiple files require filename prefix, when line numbers flag is set, empty results" |