| 1 | 1 | def grep(pattern: str, flags: str, files: list[str]) -> str: |
| 2 | | pass |
| 2 | """ |
| 3 | Search for lines matching a pattern in files and return 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 | # Edge Case: Pattern is empty |
| 27 | search_pattern = pattern.lower() if case_insensitive else pattern |
| 28 | |
| 29 | for file_path in files: |
| 30 | try: |
| 31 | with open(file_path, 'r') as file: |
| 32 | lines = file.readlines() |
| 33 | file_has_match = False |
| 34 | |
| 35 | # Edge Case: File cannot be read |
| 36 | except IOError: |
| 37 | continue |
| 38 | |
| 39 | for line_num, line in enumerate(lines, 1): |
| 40 | # Process line for case insensitivity |
| 41 | search_line = line.lower() if case_insensitive else line |
| 42 | |
| 43 | # Determine if line matches |
| 44 | if exact_match: |
| 45 | matches = search_pattern == search_line.rstrip('\n') |
| 46 | else: |
| 47 | matches = search_pattern in search_line |
| 48 | |
| 49 | # Apply invert flag |
| 50 | if invert_match: |
| 51 | matches = not matches |
| 52 | |
| 53 | if matches: |
| 54 | file_has_match = True |
| 55 | |
| 56 | # Edge Case: Only file names requested |
| 57 | if files_only: |
| 58 | break |
| 59 | |
| 60 | output_line = "" |
| 61 | |
| 62 | # Add file name if multiple files |
| 63 | if len(files) > 1: |
| 64 | output_line += f"{file_path}:" |
| 65 | |
| 66 | # Add line number if requested |
| 67 | if line_numbers: |
| 68 | output_line += f"{line_num}:" |
| 69 | |
| 70 | output_line += line |
| 71 | results.append(output_line) |
| 72 | |
| 73 | # Edge Case: Only file names requested and file has match |
| 74 | if files_only and file_has_match: |
| 75 | results.append(file_path + "\n") |
| 76 | |
| 77 | # Edge Case: No matches found |
| 78 | return ''.join(results) |
| 79 | |
| 80 | # Handled Edge Cases: Empty files list, Pattern is empty, File cannot be read, Only file names requested, No matches found |