Skip to content

Instantly share code, notes, and snippets.

@jryio
Last active July 12, 2023 12:06
Show Gist options
  • Save jryio/79f5f572baa8dc8e6d492a282c7d4fc9 to your computer and use it in GitHub Desktop.
Save jryio/79f5f572baa8dc8e6d492a282c7d4fc9 to your computer and use it in GitHub Desktop.
Adding YAML front matter to markdown files (title)
# For each result of find call our script to run on the filename
$ find . -name "*.md" -print0 | xargs -0 -I file ./prepend.sh file
# Given a file path as an argument
# 1. get the file name
# 2. prepend template string to the top of the source file
# 3. resave original source file
filepath="$1"
file_name=$(basename $filepath)
# Getting the file name (title)
md='.md'
title=${file_name%$md}
# Prepend front-matter to files
TEMPLATE="---
layout: page
title: $title
category: gen
---
"
echo "$TEMPLATE" | cat - "$filepath" > temp && mv temp "$filepath"
@jryio
Copy link
Author

jryio commented Jul 7, 2016

Use Case

This is a Bash method to add the title section of YAML front matter to N number of .md files.

Suppose you have 500+ markdown files which do not have the correct YAML front matter in order to be rendered with a static site generator like Jekyll or Hexo.

Example

Original markdown file: api-docs.md

### API

This is the documentation of the api for the RESTful service provided by unicorn.js

#### GET /names
...

Final markdown file (after script): api-docs.md

---
title: api-docs

---

### API

This is the documentation of the api for the RESTful service provided by unicorn.js

#### GET /names
...

@ottokangjian
Copy link

Thank you for you code!
I use this command line "find . -name "*.md" -print0 | xargs -0 -I file ./prepend.sh file"
and it noticed me this:
"xargs: ./prepend.sh: Permission denied"

Could you help me?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment