Skip to content

Instantly share code, notes, and snippets.

@ljmf00
Created September 10, 2019 15:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ljmf00/5222ea8a335887738c25496493ff92c2 to your computer and use it in GitHub Desktop.
Save ljmf00/5222ea8a335887738c25496493ff92c2 to your computer and use it in GitHub Desktop.
Fancy YAML parser
# YAML Parser
# This function parse a simple YAML file and pass it to individual variables
# Usage: parse_yaml <FILE> [PREFIX]
# Thanks to: https://stackoverflow.com/questions/5014632/how-can-i-parse-a-yaml-file-from-a-linux-shell-script
parse_yaml() {
local prefix=$2
local ys='[[:space:]]*' yw='[a-zA-Z0-9_]*'
local fs
fs=$(echo @|tr @ '\034')
sed -ne "s|^\($ys\):|\1|" \
-e "s|^\($ys\)\($yw\)$ys:${ys}[\"']\(.*\)[\"']$ys\$|\1$fs\2$fs\3|p" \
-e "s|^\($ys\)\($yw\)$ys:$ys\(.*\)$ys\$|\1$fs\2$fs\3|p" "$1" |
awk "-F$fs" '{
indent = length($1)/2;
vname[indent] = $2;
for (i in vname) {if (i > indent) {delete vname[i]}}
if (length($3) > 0) {
vn=""; for (i=0; i<indent; i++) {vn=(vn)(vname[i])("_")}
printf("%s%s%s=\"%s\"\n", "'"$prefix"'",vn, $2, $3);
}
}'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment