Skip to content

Instantly share code, notes, and snippets.

@lamberta
Created March 5, 2012 05:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lamberta/1976876 to your computer and use it in GitHub Desktop.
Save lamberta/1976876 to your computer and use it in GitHub Desktop.
Parse metadata variables from a markdown file.
#!/usr/bin/env bash
##
## Parse metadata variables from a markdown file.
##
## The key-values are returned as field-deliminated lines to
## stdout, or, as a variable string that can be passed to pandoc
## as command-line parameters.
##
## Delcare metadata in the markdown file using the format:
## % meta keyname1="value1"
## %meta keyname2="value2"
## % meta keyname3="value3"
##
## As you can see, some of the separating space is optional.
META_REGEX="^%\s*meta\s*"
SEP="="
function print_help {
echo "Usage: $(basename $0) [options] -f file"
echo " -f=file Markdown file to parse metadata from."
echo " -P Return a variable declaration string for pandoc."
echo " -S=sep Use a different field separator. [=]"
echo " -h Show this usage guide."
}
while getopts "f:PS:h" opt; do
case $opt in
f) FILE="$OPTARG";;
P) OPT_PANDOC=1;;
S) SEP="$OPTARG";;
h) print_help; exit 0;;
\?) print_help; exit 0;;
esac
done
if [ ! -f "$FILE" ]; then
print_help
exit 1
fi
##parse metadata
##
declare -A METADATA
while read line; do
kv=$(echo "$line" | sed -e "s/$META_REGEX\(\w*\)/\1/g")
key=$(echo "$kv" | cut -d '=' -f1)
val=$(echo "$kv" | cut -d '=' -f2)
METADATA["$key"]="$val"
done < <(cat "$FILE" | grep -P "$META_REGEX")
##print output
##
for key in "${!METADATA[@]}"; do
if [ -n "$OPT_PANDOC" ]; then
pandoc_params="$pandoc_params -V $key=${METADATA[$key]}"
else
echo "$key$SEP${METADATA[$key]}"
fi
done
if [ -n "$OPT_PANDOC" ]; then
echo "$pandoc_params"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment