| 1 | 1 | def grep(pattern: str, flags: str, files: list[str]) -> str: |
| 2 | | pass |
| 2 | # Parse flags |
| 3 | line_numbers = '-n' in flags |
| 4 | files_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() |
| 15 | |
| 16 | # Process each file |
| 17 | for filename in files: |
| 18 | try: |
| 19 | with open(filename, 'r', encoding='utf-8') as file: |
| 20 | # Edge Case: Handle files that cannot be opened |
| 21 | lines = file.readlines() |
| 22 | except FileNotFoundError: |
| 23 | # Edge Case: File not found - skip file |
| 24 | continue |
| 25 | except Exception: |
| 26 | # Edge Case: Other file reading errors - skip file |
| 27 | continue |
| 28 | |
| 29 | # Process each line in the file |
| 30 | for line_num, line in enumerate(lines, start=1): |
| 31 | # Prepare line for comparison |
| 32 | compare_line = line.lower() if case_insensitive else line |
| 33 | |
| 34 | # Determine if line matches |
| 35 | if exact_match: |
| 36 | # Edge Case: Exact match flag - match entire line |
| 37 | matches = (compare_line.rstrip('\n\r') == search_pattern) |
| 38 | else: |
| 39 | # Edge Case: Partial match - substring search |
| 40 | matches = (search_pattern in compare_line) |
| 41 | |
| 42 | # Apply invert flag |
| 43 | if invert_match: |
| 44 | # Edge Case: Invert match flag - flip match result |
| 45 | matches = not matches |
| 46 | |
| 47 | # If line matches, collect results |
| 48 | if matches: |
| 49 | # Edge Case: Files only flag - collect only filenames |
| 50 | if files_only: |
| 51 | matched_files.add(filename) |
| 52 | # Optimization: Break early when we only need to know if file matches |
| 53 | break |
| 54 | else: |
| 55 | # Build output line |
| 56 | output_line = "" |
| 57 | # Edge Case: Multiple files - prepend filename |
| 58 | if len(files) > 1: |
| 59 | output_line += f"{filename}:" |
| 60 | # Edge Case: Line numbers flag - prepend line number |
| 61 | if line_numbers: |
| 62 | output_line += f"{line_num}:" |
| 63 | output_line += line |
| 64 | results.append(output_line) |
| 65 | |
| 66 | # Edge Case: Files only flag - return only filenames |
| 67 | if files_only: |
| 68 | # Return filenames in the order they were encountered |
| 69 | ordered_matches = [f for f in files if f in matched_files] |
| 70 | return "\n".join(ordered_matches) + ("\n" if ordered_matches else "") |
| 71 | |
| 72 | # Edge Case: No matches - return empty string |
| 73 | return "".join(results) |
| 74 | |
| 75 | # Handled Edge Cases: Empty files list, File not found, Other file reading errors, Exact match flag, Partial match, Invert match flag, Files only flag, Multiple files, Line numbers flag, No matches |