| 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 | # Edge Case: Empty pattern |
| 21 | if not pattern: |
| 22 | pattern_to_match = '' |
| 23 | else: |
| 24 | pattern_to_match = pattern.lower() if case_insensitive else pattern |
| 25 | |
| 26 | result_lines = [] |
| 27 | matching_files = set() |
| 28 | |
| 29 | # Edge Case: No files provided |
| 30 | if not files: |
| 31 | return "" |
| 32 | |
| 33 | multiple_files = len(files) > 1 |
| 34 | |
| 35 | for file_path in files: |
| 36 | try: |
| 37 | with open(file_path, 'r', encoding='utf-8') as f: |
| 38 | lines = f.readlines() |
| 39 | except FileNotFoundError: |
| 40 | # Edge Case: File not found - skip the file |
| 41 | continue |
| 42 | except Exception: |
| 43 | # Edge Case: Other file reading errors - skip the file |
| 44 | continue |
| 45 | |
| 46 | # Edge Case: Empty file |
| 47 | if not lines: |
| 48 | continue |
| 49 | |
| 50 | for line_num, line in enumerate(lines, 1): |
| 51 | # Prepare line for comparison |
| 52 | line_to_check = line |
| 53 | if case_insensitive: |
| 54 | line_to_check = line.lower() |
| 55 | |
| 56 | # Determine if line matches |
| 57 | if exact_match: |
| 58 | matches = pattern_to_match == line_to_check.rstrip('\n\r') |
| 59 | else: |
| 60 | matches = pattern_to_match in line_to_check |
| 61 | |
| 62 | # Apply invert flag |
| 63 | if invert_match: |
| 64 | matches = not matches |
| 65 | |
| 66 | if matches: |
| 67 | if files_only: |
| 68 | matching_files.add(file_path) |
| 69 | # No need to check other lines in this file |
| 70 | break |
| 71 | else: |
| 72 | output_line = "" |
| 73 | if multiple_files: |
| 74 | output_line += f"{file_path}:" |
| 75 | if line_numbers: |
| 76 | output_line += f"{line_num}:" |
| 77 | output_line += line |
| 78 | result_lines.append(output_line) |
| 79 | |
| 80 | # Edge Case: -l flag with no matches |
| 81 | if files_only: |
| 82 | return "\n".join(sorted(list(matching_files))) + ("\n" if matching_files else "") |
| 83 | |
| 84 | # Edge Case: No matches found |
| 85 | if not result_lines: |
| 86 | return "" |
| 87 | |
| 88 | return "".join(result_lines) |
| 89 | |
| 90 | # Handled Edge Cases: Empty pattern, no files provided, file not found, other file reading errors, empty file, -l flag with no matches, no matches found |