Remove YAML Front Matter

There are many ways to remove YAML Front Matter, here is how I use sed to do so:

1
sed -i '1 { /^---/ { :a N; /\n---/! ba; d} }' INPUT_FILE

Explanation:

1
2
3
4
5
6
7
8
9
10
11
1 { # in the first line
/^---/ { # if it starts with ---
:a # jump label for looping
N # fetch the next line, append to pattern space
/\n---/! ba; # if the result does not contain \n--- (that is, if the last
# fetched line does not begin with ---), go back to :a
d # then delete the whole thing.
}
}
# otherwise drop off the end here and do the default (print
# the line)

Furthermore, if you wanna keep some useful metadata in front matter like post title in blogging system, you can do so:

1
2
3
title=$(grep '^title\:\(.*\)$' $1 | sed -e 's/title\:\s//g')
sed -i -e "/---/a # `echo $title`" $1
sed -i '1 { /^---/ { :a N; /\n---/! ba; d} }' $1

Here is a workaround to insert $title in each --- then remove YAML Front Matter.

References: