| 1 | 1 | def grep(pattern: str, flags: str, files: list[str]) -> str: |
| 2 | | pass |
| 2 | """ |
| 3 | Search files for lines matching a search string and return all matching lines. |
| 4 | |
| 5 | Args: |
| 6 | pattern: The string to search for |
| 7 | flags: String containing command line flags (-n, -l, -i, -v, -x) |
| 8 | files: List of file paths to search in |
| 9 | |
| 10 | Returns: |
| 11 | String containing all matching lines, formatted according to flags |
| 12 | """ |
| 13 | # Parse flags |
| 14 | line_numbers = '-n' in flags |
| 15 | files_only = '-l' in flags |
| 16 | case_insensitive = '-i' in flags |
| 17 | invert_match = '-v' in flags |
| 18 | exact_match = '-x' in flags |
| 19 | |
| 20 | results = [] |
| 21 | |
| 22 | # Edge Case: Empty files list |
| 23 | if not files: |
| 24 | return "" |
| 25 | |
| 26 | multiple_files = len(files) > 1 |
| 27 | |
| 28 | for file_path in files: |
| 29 | # Edge Case: File not found |
| 30 | try: |
| 31 | with open(file_path, 'r') as file: |
| 32 | lines = file.readlines() |
| 33 | except FileNotFoundError: |
| 34 | # According to typical grep behavior, we silently skip missing files |
| 35 | continue |
| 36 | |
| 37 | file_has_match = False |
| 38 | |
| 39 | for line_num, line in enumerate(lines, 1): |
| 40 | # Remove newline for processing but keep it for output |
| 41 | line_content = line.rstrip('\n') |
| 42 | |
| 43 | # Determine if line matches |
| 44 | if case_insensitive: |
| 45 | match = pattern.lower() in line_content.lower() |
| 46 | exact = pattern.lower() == line_content.lower() |
| 47 | else: |
| 48 | match = pattern in line_content |
| 49 | exact = pattern == line_content |
| 50 | |
| 51 | # Edge Case: Exact match flag |
| 52 | if exact_match: |
| 53 | match = exact |
| 54 | |
| 55 | # Edge Case: Invert match flag |
| 56 | if invert_match: |
| 57 | match = not match |
| 58 | |
| 59 | if match: |
| 60 | file_has_match = True |
| 61 | |
| 62 | # Edge Case: Files only flag - we don't need line details |
| 63 | if files_only: |
| 64 | break |
| 65 | |
| 66 | output_line = "" |
| 67 | |
| 68 | # Edge Case: Multiple files - prepend filename |
| 69 | if multiple_files: |
| 70 | output_line += f"{file_path}:" |
| 71 | |
| 72 | # Edge Case: Line numbers flag |
| 73 | if line_numbers: |
| 74 | output_line += f"{line_num}:" |
| 75 | |
| 76 | output_line += line |
| 77 | results.append(output_line) |
| 78 | |
| 79 | # Edge Case: Files only flag - add filename if it had a match |
| 80 | if files_only and file_has_match: |
| 81 | results.append(file_path + "\n") |
| 82 | |
| 83 | # Edge Case: Empty results |
| 84 | if not results: |
| 85 | return "" |
| 86 | |
| 87 | return ''.join(results) |
| 88 | # Handled Edge Cases: Empty files list, File not found, Exact match flag, Invert match flag, Files only flag, Multiple files flag, Line numbers flag, Empty results" |