| 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 | matched_files = set() |
| 22 | |
| 23 | # Edge Case: Empty files list |
| 24 | if not files: |
| 25 | return "" |
| 26 | |
| 27 | multiple_files = len(files) > 1 |
| 28 | |
| 29 | # Process each file |
| 30 | for file_path in files: |
| 31 | try: |
| 32 | with open(file_path, 'r', encoding='utf-8') as file: |
| 33 | lines = file.readlines() |
| 34 | |
| 35 | # Edge Case: File cannot be read |
| 36 | except IOError: |
| 37 | continue |
| 38 | |
| 39 | # Process each line in the file |
| 40 | for line_num, line in enumerate(lines, 1): |
| 41 | # Prepare strings for comparison based on case sensitivity |
| 42 | search_pattern = pattern.lower() if case_insensitive else pattern |
| 43 | search_line = line.lower() if case_insensitive else line |
| 44 | |
| 45 | # Determine if line matches |
| 46 | if exact_match: |
| 47 | is_match = search_line.rstrip('\n\r') == search_pattern |
| 48 | else: |
| 49 | is_match = search_pattern in search_line |
| 50 | |
| 51 | # Apply invert flag |
| 52 | if invert_match: |
| 53 | is_match = not is_match |
| 54 | |
| 55 | # If line matches pattern (considering invert flag) |
| 56 | if is_match: |
| 57 | # Edge Case: Only file names requested (-l flag) |
| 58 | if files_only: |
| 59 | matched_files.add(file_path) |
| 60 | break # No need to check more lines in this file |
| 61 | else: |
| 62 | # Build output line |
| 63 | output_line = "" |
| 64 | |
| 65 | # Add file name prefix if multiple files |
| 66 | if multiple_files: |
| 67 | output_line += f"{file_path}:" |
| 68 | |
| 69 | # Add line number if requested |
| 70 | if line_numbers: |
| 71 | output_line += f"{line_num}:" |
| 72 | |
| 73 | # Add the actual line content |
| 74 | output_line += line |
| 75 | results.append(output_line) |
| 76 | |
| 77 | # Edge Case: Only file names requested (-l flag) |
| 78 | if files_only: |
| 79 | return "\n".join(sorted(matched_files)) + ("\n" if matched_files else "") |
| 80 | |
| 81 | # Edge Case: No matches found |
| 82 | return "".join(results) |
| 83 | |
| 84 | # Handled Edge Cases: Empty files list, File cannot be read, Only file names requested (-l flag), No matches found |