| 1 | 1 | def grep(pattern: str, flags: str, files: list[str]) -> str: |
| 2 | | pass |
| 2 | # Parse flags (handle both "-n -i" and "-ni" formats) |
| 3 | flag_list = flags.split() if ' ' in flags else list(flags) if flags else [] |
| 4 | line_numbers = '-n' in flag_list or 'n' in flag_list |
| 5 | files_only = '-l' in flag_list or 'l' in flag_list |
| 6 | case_insensitive = '-i' in flag_list or 'i' in flag_list |
| 7 | invert_match = '-v' in flag_list or 'v' in flag_list |
| 8 | exact_match = '-x' in flag_list or 'x' in flag_list |
| 9 | |
| 10 | # Prepare pattern for comparison |
| 11 | search_pattern = pattern.lower() if case_insensitive else pattern |
| 12 | |
| 13 | # Results storage |
| 14 | results = [] |
| 15 | matched_files = set() |
| 16 | |
| 17 | # Process each file |
| 18 | for filename in files: |
| 19 | try: |
| 20 | with open(filename, 'r', encoding='utf-8') as file: |
| 21 | lines = file.readlines() |
| 22 | except FileNotFoundError: |
| 23 | # Edge Case: File not found - skip the file |
| 24 | continue |
| 25 | |
| 26 | # Process each line |
| 27 | for line_num, line in enumerate(lines, 1): |
| 28 | # Prepare line for comparison |
| 29 | compare_line = line.lower() if case_insensitive else line |
| 30 | |
| 31 | # Determine if line matches |
| 32 | if exact_match: |
| 33 | matches = (compare_line.rstrip('\n') == search_pattern) |
| 34 | else: |
| 35 | matches = (search_pattern in compare_line) |
| 36 | |
| 37 | # Apply invert flag |
| 38 | if invert_match: |
| 39 | matches = not matches |
| 40 | |
| 41 | # If line matches pattern (after considering invert) |
| 42 | if matches: |
| 43 | matched_files.add(filename) |
| 44 | |
| 45 | # If we only need file names, we don't need to build output lines |
| 46 | if files_only: |
| 47 | continue |
| 48 | |
| 49 | # Build output line |
| 50 | output_line = "" |
| 51 | |
| 52 | # Add filename prefix if multiple files |
| 53 | if len(files) > 1: |
| 54 | output_line += f"{filename}:" |
| 55 | |
| 56 | # Add line number if requested |
| 57 | if line_numbers: |
| 58 | output_line += f"{line_num}:" |
| 59 | |
| 60 | # Add the actual line content |
| 61 | output_line += line |
| 62 | |
| 63 | results.append(output_line) |
| 64 | |
| 65 | # Process all lines in the file regardless of matches found |
| 66 | pass |
| 67 | |
| 68 | # If files_only flag is set, return only the filenames |
| 69 | if files_only: |
| 70 | # Maintain the order of files as they appear in the input |
| 71 | ordered_matched_files = [f for f in files if f in matched_files] |
| 72 | return "\n".join(ordered_matched_files) + ("\n" if ordered_matched_files else "") |
| 73 | |
| 74 | # Otherwise return the matching lines |
| 75 | return "".join(results) |
| 76 | |
| 77 | # Handled Edge Cases: File not found, empty files list, case insensitive matching, exact line matching, invert matching, line numbering, files only output, multiple files with prefixes |