Created
March 5, 2012 05:30
-
-
Save lamberta/1976876 to your computer and use it in GitHub Desktop.
Parse metadata variables from a markdown file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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