Fryboyter

Insert content at the end of the front matter area

When I write an article for fryboyter.de, I create a Markdown file with a front matter area at the beginning. This looks like this, for example.

---
title: Insert content at the end of the front matter area
date: 2022-11-02T20:21:11+0100
categories:
- General
tags:
- Front Matter
- Markdown
- Sed
slug: insert-content-at-the-end-of-the-front-matter-area
---

In some cases, you may want to extend this area later. For example, with nositemap: true so that the article does not appear in the sitemap of the website. For a single article, this can be done quickly by changing the file manually. But what if it affects not one but several files? Then it would be better to automate the changes. However, the area in question does not always consist of the same number of lines. For example, because sometimes I use more tags, sometimes less. Finally, I came to the following solution.

for file in $(find . -type f -name "*.md");
do
lines=$( sed -n '/^---$/=' $file | sed -n 2p )
sed -i -e "$lines i nositemap: true" $file
done

The first line searches the current directory and all subdirectories therein for files with the extension .md. The third line checks how many lines the respective front matter area consists of. The fourth line adds nositemap: true to the end of the front matter area so it looks like this.

---
title: Insert content at the end of the front matter area
date: 2022-11-02T20:21:11+0100
categories:
- General
tags:
- Front Matter
- Markdown
- Sed
slug: insert-content-at-the-end-of-the-front-matter-area
nositemap: true
---

If you want to test the script first without changing the files directly, you should remove the -i parameter in line 4. Then the changed files are only displayed without actually being changed.

General