Skip to content

Instantly share code, notes, and snippets.

@gustavomdsantos
Created January 18, 2019 16:45
Show Gist options
  • Save gustavomdsantos/8a3eff073765c43ce5cd25cdc7856500 to your computer and use it in GitHub Desktop.
Save gustavomdsantos/8a3eff073765c43ce5cd25cdc7856500 to your computer and use it in GitHub Desktop.
Bash-only parser that leverages sed and awk to parse simple yaml files.
##
# Bash-only parser that leverages sed and awk to parse simple yaml files.
# Code based from: http://stackoverflow.com/a/21189044
# Usage: eval $(parse_yaml sample.yml)
# or
# Usage: variable = parse_yaml sample.yml
#
# @param $1 the path of the .yml file
# @param $2 an optional prefix to the name of the variables
# @author stefan-farestam
# @author gustavosotnas
##
parse_yaml() {
local prefix=$2
local s='[[:space:]]*' w='[a-zA-Z0-9_]*' fs=$(echo @|tr @ '\034')
if [ ! -f "$1" ] # if the .yml file exists
then
return 1; # the file doesn't exists.
fi
2>/dev/null sed -ne "s|^\($s\):|\1|" \
-e "s|^\($s\)\($w\)$s:$s[\"']\(.*\)[\"']$s\$|\1$fs\2$fs\3|p" \
-e "s|^\($s\)\($w\)$s:$s\(.*\)$s\$|\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);
}
}'
if [ "$?" != "0" ]
then
return 1;
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment