| 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 based on flags. |
| 4 | |
| 5 | Args: |
| 6 | pattern: The string to search for |
| 7 | flags: String containing flag characters (-n, -l, -i, -v, -x) |
| 8 | files: List of file paths to search in |
| 9 | |
| 10 | Returns: |
| 11 | String with 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 | matched_files = set() |
| 22 | |
| 23 | # Edge Case: Empty files list |
| 24 | if not files: |
| 25 | return "" |
| 26 | |
| 27 | # Edge Case: Empty pattern |
| 28 | search_pattern = pattern.lower() if case_insensitive else pattern |
| 29 | |
| 30 | multiple_files = len(files) > 1 |
| 31 | |
| 32 | for file_path in files: |
| 33 | try: |
| 34 | # Edge Case: File not found or inaccessible |
| 35 | with open(file_path, 'r', encoding='utf-8') as file: |
| 36 | for line_num, line in enumerate(file, 1): |
| 37 | # Process line for case insensitivity |
| 38 | compare_line = line.lower().rstrip('\n') if case_insensitive else line.rstrip('\n') |
| 39 | |
| 40 | # Determine if line matches |
| 41 | if exact_match: |
| 42 | matches = (compare_line == search_pattern) |
| 43 | else: |
| 44 | matches = (search_pattern in compare_line) |
| 45 | |
| 46 | # Apply invert flag |
| 47 | if invert_match: |
| 48 | matches = not matches |
| 49 | |
| 50 | if matches: |
| 51 | # Edge Case: Only file names requested |
| 52 | if files_only: |
| 53 | matched_files.add(file_path) |
| 54 | break # No need to check more lines in this file |
| 55 | else: |
| 56 | output_line = line.rstrip('\n') |
| 57 | |
| 58 | # Build output with appropriate prefixes |
| 59 | if multiple_files: |
| 60 | output_line = f"{file_path}:{output_line}" |
| 61 | |
| 62 | if line_numbers: |
| 63 | if multiple_files: |
| 64 | # Insert line number after filename |
| 65 | parts = output_line.split(':', 1) |
| 66 | output_line = f"{parts[0]}:{line_num}:{parts[1] if len(parts) > 1 else ''}" |
| 67 | else: |
| 68 | output_line = f"{line_num}:{output_line}" |
| 69 | |
| 70 | results.append(output_line) |
| 71 | except FileNotFoundError: |
| 72 | # Edge Case: File not found - continue with other files |
| 73 | continue |
| 74 | except IOError: |
| 75 | # Edge Case: Other I/O error - continue with other files |
| 76 | continue |
| 77 | |
| 78 | # Edge Case: Only file names requested |
| 79 | if files_only: |
| 80 | return '\n'.join(sorted(matched_files)) |
| 81 | |
| 82 | return '\n'.join(results) |
| 83 | |
| 84 | # Handled Edge Cases: Empty files list, Empty pattern, File not found or inaccessible, Only file names requested" |