gemini-2.5-pro-preview-05-06· Google LMArena Human Preference 140K
I have a few Markdown files in a directory. Each file has YAML frontmatter. I'd like to…
- User
I have a few Markdown files in a directory. Each file has YAML frontmatter. I'd like to print the content of all files, but replace the markdown frontmatter with "\n***\n".
- Assistant
Okay, this is a common task. We can use Python for this. The strategy will be:
- List Markdown Files: Get all
.mdfiles in the current directory (or a specified one). - Read Each File: Open and read the content of each file.
- Identify and Replace Frontmatter: Use a regular expression to find the YAML frontmatter (which starts and ends with
---at the beginning of the file). - Print Modified Content: Print the result.
Here's a Python script to do that:
import re from pathlib import Path def process_markdown_files(directory_path="."): """ Processes all Markdown files in a given directory. It replaces the YAML frontmatter with "\n***\n" and prints the result. """ target_dir = Path(directory_path) replacement_text = "\n***\n" # Regex to find YAML frontmatter at the START of the file. # - `^`: Matches the beginning of the string. # - `\s*---\s*\n`: Matches the opening '---', possibly surrounded by whitespace, on its own line. # - `.*?`: Matches any character (including newlines due to re.DOTALL) non-greedily. # - `\n\s*---\s*`: Matches the closing '---', possibly surrounded by whitespace, on its own line. # - `(\n|$)`: Matches either a newline after the closing '---' or the end of the string # (in case the frontmatter is the last thing in the file or no newline after it). # - `re.DOTALL`: Makes '.' match newlines as well. frontmatter_regex = re.compile(r"^\s*---\s*\n.*?\n\s*---\s*(\n|$)", re.DOTALL) markdown_files = list(target_dir.glob("*.md")) if not markdown_files: print(f"No Markdown files (.md) found in '{target_dir.resolve()}'.") return for md_file in markdown_files: print(f"--- Content of: {md_file.name} ---") try: content = md_file.read_text(encoding="utf-8") # Replace only the first occurrence (which should be the frontmatter) modified_content, num_replacements = frontmatter_regex.subn(replacement_text, content, count=1) if num_replacements == 0: print(f"(No frontmatter found in {md_file.name})") print(content) # Print original if no frontmatter else: # If the replacement text starts with \n, and the content after frontmatter # also starts with \n, we might get an extra blank line. # The replacement_text already includes leading/trailing newlines as desired. print(modified_content.strip("\n")) # Print modified, strip any extra leading/trailing newlines from print except Exception as e: print(f"Error processing file {md_file.name}: {e}") print("\n---------------------------\n") if __name__ == "__main__": # By default, processes files in the current directory. # You can specify a different directory like this: # process_markdown_files("/path/to/your/markdown_files") process_markdown_files(".")How to use it:
- Save: Save the code above as a Python file (e.g.,
process_md.py). - Place: Put this script in the directory containing your Markdown files, or modify the
directory_pathvariable in theprocess_markdown_files()call at the bottom. - Run: Open a terminal or command prompt, navigate to where you saved the script (if it's not already in the target directory), and run:
python process_md.py
Explanation of the Regex:
^: Anchors the match to the beginning of the string (the file content).\s*---\s*\n: Matches the opening---.\s*: Zero or more whitespace characters (handles potential spaces before/after---).---: Literal---.\n: A newline character.
.*?: Matches any character (.) zero or more times (*), but as few as possible (?- non-greedy). This is important so it stops at the next---and doesn't consume the whole file if there are other---sequences later in the Markdown body.\n\s*---\s*: Matches the closing---on its own line.(\n|$): This part is crucial. It ensures the closing---is followed by either:\n: A newline (if there's content after the frontmatter).$: The end of the string (if the frontmatter is the very last thing in the file).
re.DOTALL: This flag makes the.special character match any character at all, including a newline. Without it,.would not match newlines, and the.*?part wouldn't span across multiple lines of YAML.frontmatter_regex.subn(replacement_text, content, count=1):subnis likesubbut returns a tuple(new_string, number_of_subs_made).count=1ensures that only the first match (which should be the frontmatter at the beginning) is replaced. This prevents accidental replacement of---sequences used as horizontal rules later in the Markdown.
This script should reliably find and replace the YAML frontmatter block.
- List Markdown Files: Get all
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.