| 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 zero or more 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_search = '' |
| 23 | else: |
| 24 | pattern_to_search = 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 file: |
| 38 | lines = file.readlines() |
| 39 | |
| 40 | # Edge Case: File cannot be read |
| 41 | except IOError: |
| 42 | continue |
| 43 | |
| 44 | for line_num, line in enumerate(lines, start=1): |
| 45 | # Prepare line for comparison |
| 46 | line_to_check = line |
| 47 | if case_insensitive: |
| 48 | line_to_check = line.lower() |
| 49 | |
| 50 | # Determine if line matches |
| 51 | if exact_match: |
| 52 | matches = pattern_to_search == line_to_check.rstrip('\n\r') |
| 53 | else: |
| 54 | matches = pattern_to_search in line_to_check |
| 55 | |
| 56 | # Apply invert flag |
| 57 | if invert_match: |
| 58 | matches = not matches |
| 59 | |
| 60 | if matches: |
| 61 | # Edge Case: Only file names requested |
| 62 | if files_only: |
| 63 | matching_files.add(file_path) |
| 64 | break # Found a match, no need to check more lines in this file |
| 65 | else: |
| 66 | output_line = "" |
| 67 | # Add file name prefix if multiple files |
| 68 | if multiple_files: |
| 69 | output_line += f"{file_path}:" |
| 70 | # Add line number if requested |
| 71 | if line_numbers: |
| 72 | output_line += f"{line_num}:" |
| 73 | # Add the actual line |
| 74 | output_line += line |
| 75 | result_lines.append(output_line) |
| 76 | |
| 77 | # Edge Case: Only file names requested |
| 78 | if files_only: |
| 79 | return "\n".join(sorted(list(matching_files))) + ("\n" if matching_files else "") |
| 80 | |
| 81 | return "".join(result_lines) |
| 82 | |
| 83 | # Handled Edge Cases: Empty pattern, No files provided, File cannot be read, Only file names requested" |