| 1 | 1 | def grep(pattern: str, flags: str, files: list[str]) -> str: |
| 2 | | pass |
| 2 | # Edge Case: Handle empty pattern |
| 3 | if not pattern: |
| 4 | return "" |
| 5 | |
| 6 | # Edge Case: Handle empty files list |
| 7 | if not files: |
| 8 | return "" |
| 9 | |
| 10 | # Parse flags |
| 11 | line_numbers = '-n' in flags |
| 12 | filenames_only = '-l' in flags |
| 13 | case_insensitive = '-i' in flags |
| 14 | invert_match = '-v' in flags |
| 15 | exact_match = '-x' in flags |
| 16 | |
| 17 | # Prepare pattern for comparison |
| 18 | search_pattern = pattern.lower() if case_insensitive else pattern |
| 19 | |
| 20 | # Results storage |
| 21 | results = [] |
| 22 | matching_files = set() |
| 23 | |
| 24 | # Process each file |
| 25 | for filename in files: |
| 26 | try: |
| 27 | with open(filename, 'r') as file: |
| 28 | lines = file.readlines() |
| 29 | except FileNotFoundError: |
| 30 | # Edge Case: Handle file not found |
| 31 | continue |
| 32 | |
| 33 | # Process each line |
| 34 | for line_num, line in enumerate(lines, start=1): |
| 35 | # Prepare line for comparison |
| 36 | compare_line = line.lower() if case_insensitive else line |
| 37 | |
| 38 | # Determine if line matches |
| 39 | if exact_match: |
| 40 | match = (compare_line.rstrip('\n') == search_pattern) |
| 41 | else: |
| 42 | match = (search_pattern in compare_line) |
| 43 | |
| 44 | # Apply invert flag |
| 45 | if invert_match: |
| 46 | match = not match |
| 47 | |
| 48 | # If line matches pattern (considering invert) |
| 49 | if match: |
| 50 | if filenames_only: |
| 51 | matching_files.add(filename) |
| 52 | # No need to process more lines in this file |
| 53 | break |
| 54 | else: |
| 55 | # Build output line |
| 56 | output_line = "" |
| 57 | if len(files) > 1: |
| 58 | output_line += f"{filename}:" |
| 59 | if line_numbers: |
| 60 | output_line += f"{line_num}:" |
| 61 | output_line += line |
| 62 | results.append(output_line) |
| 63 | |
| 64 | # Edge Case: Handle -l flag (filenames only) |
| 65 | if filenames_only: |
| 66 | return "\n".join(sorted(matching_files)) + ("\n" if matching_files else "") |
| 67 | |
| 68 | # Edge Case: Handle no matches found |
| 69 | if not results: |
| 70 | return "" |
| 71 | |
| 72 | # Join results with newlines |
| 73 | return "".join(results) |
| 74 | |
| 75 | # Handled Edge Cases: empty pattern, empty files list, file not found, no matches found, -l flag (filenames only) |