Detect if the file starts with ---, then strip out everything up to the next ---.

how-to-remove-markdown-frontmatter-programmatically

Today I learned how to strip out YAML frontmatter (--- … ---) from Markdown files using either Python or a shell script.

✼ Python approach

def remove_frontmatter(md_content):
if md_content.startswith("---"):
# Split the Markdown content into three parts
# parts[0] = "" (before first ---)
# parts[1] = YAML frontmatter
# parts[2] = rest of the markdown
parts = md_content.split("---", 2)
if len(parts) > 2:
return parts[2].lstrip("\n")
return md_content

✼ Shell script approach

#!/bin/sh
if [ -f "$file" ] && head -n1 "$file" | grep -q '^---$'; then
sed '1,/^---$/d' "$file" > "$file.tmp" && mv "$file.tmp" "$file"
fi

Key takeaway: Whether in Python or shell, the idea is the same—detect if the file starts with ---, then strip out everything up to the next ---.

Thanks for reading! If you found this page useful, consider buying me a coffee.
© 2025 Hua-Ming Huang · licensed under CC BY 4.0