| 1 | | def grep(pattern: str, flags: str, files: list[str]) -> str: |
| 2 | | pass |
| 1 | def grep(pattern, flags, files): |
| 2 | """ |
| 3 | Search for pattern in files and return matching lines. |
| 4 | |
| 5 | Args: |
| 6 | pattern (str): The string to search for |
| 7 | flags (str): Space-separated string of flags (-n, -l, -i, -v, -x) |
| 8 | files (list): List of file paths to search in |
| 9 | |
| 10 | Returns: |
| 11 | str: Matching lines or filenames, formatted according to flags |
| 12 | """ |
| 13 | # Parse flags |
| 14 | flag_list = flags.split() if flags else [] |
| 15 | line_numbers = "-n" in flag_list |
| 16 | filenames_only = "-l" in flag_list |
| 17 | case_insensitive = "-i" in flag_list |
| 18 | invert_match = "-v" in flag_list |
| 19 | exact_match = "-x" in flag_list |
| 20 | |
| 21 | # Prepare pattern for comparison |
| 22 | search_pattern = pattern.lower() if case_insensitive else pattern |
| 23 | |
| 24 | results = [] |
| 25 | matching_files = [] # For -l flag |
| 26 | |
| 27 | for file_path in files: |
| 28 | try: |
| 29 | with open(file_path, "r", encoding="utf-8") as file: |
| 30 | for line_num, line in enumerate(file, 1): |
| 31 | # Remove trailing newline for processing |
| 32 | line_content = line.rstrip("\n") |
| 33 | |
| 34 | # Prepare line for comparison |
| 35 | compare_line = line_content.lower() if case_insensitive else line_content |
| 36 | |
| 37 | # Check for match based on flags |
| 38 | if exact_match: |
| 39 | is_match = (compare_line == search_pattern) |
| 40 | else: |
| 41 | is_match = (search_pattern in compare_line) |
| 42 | |
| 43 | # Apply invert flag |
| 44 | if invert_match: |
| 45 | is_match = not is_match |
| 46 | |
| 47 | # If line matches (or doesn't match with -v) |
| 48 | if is_match: |
| 49 | if filenames_only: |
| 50 | if file_path not in matching_files: |
| 51 | matching_files.append(file_path) |
| 52 | # We can break early for this file since we only need to know it matches |
| 53 | break |
| 54 | else: |
| 55 | # Build output line |
| 56 | output_line = "" |
| 57 | if len(files) > 1: |
| 58 | output_line += f"{file_path}:" |
| 59 | if line_numbers: |
| 60 | output_line += f"{line_num}:" |
| 61 | output_line += line_content |
| 62 | results.append(output_line) |
| 63 | except FileNotFoundError: |
| 64 | # Silently skip missing files as per typical grep behavior |
| 65 | continue |
| 66 | |
| 67 | # Handle -l flag: return only filenames |
| 68 | if filenames_only: |
| 69 | # Preserve order of files as they were processed |
| 70 | ordered_matching_files = [f for f in files if f in matching_files] |
| 71 | return "\n".join(ordered_matching_files) + ("\n" if ordered_matching_files else "") |
| 72 | |
| 73 | # Return results with newlines |
| 74 | if len(results) > 0: |
| 75 | return "\n".join(results) + "\n" |
| 76 | else: |
| 77 | return "" |