Skip to content

Instantly share code, notes, and snippets.

@DinoChiesa
Created October 20, 2015 03:53
Show Gist options
  • Select an option

  • Save DinoChiesa/3e3c3866b51290f31243 to your computer and use it in GitHub Desktop.

Select an option

Save DinoChiesa/3e3c3866b51290f31243 to your computer and use it in GitHub Desktop.
development:
adapter: mysql2
encoding: utf8
database: my_database
username: root
roles:
- admin
- developer
- guest
password:
users:
-
name: pineapple
role: admin
-
name: umbrella
role: developer
development_adapter=("mysql2")
development_encoding=("utf8")
development_database=("my_database")
development_username=("root")
development_roles+=("admin")
development_roles+=("developer")
development_roles+=("guest")
development_users__name+=("pineapple")
development_users__role+=("admin")
development_users__name+=("umbrella")
development_users__role+=("developer")
## derived from https://gist.github.com/epiloque/8cf512c6d64641bde388
## works for arrays of hashes, as long as the hashes do not have arrays
parse_yaml2() {
local prefix=$2
local s
local w
local fs
s='[[:space:]]*'
w='[a-zA-Z0-9_]*'
fs="$(echo @|tr @ '\034')"
sed -ne "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;
if (length($2) == 0) { conj[indent]="+";} else {conj[indent]="";}
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=(\"%s\")\n", "'"$prefix"'",vn, $2, conj[indent-1],$3);
}
}' | sed 's/_=/+=/g'
}
@DinoChiesa

Copy link
Copy Markdown
Author

This sort of works for arrays of hashes, except the hashes cannot themselves contain arrays.
Also you need to code around it. Basically you get N bash arrays , one for each property in the hash.

@bjne

bjne commented Sep 21, 2016

Copy link
Copy Markdown

this one does not handle string with doublequotes inside

@armarti

armarti commented Apr 9, 2017

Copy link
Copy Markdown

This is a really great function. I needed mine to work with dashes "-" in the keynames so I added \- to the regex on line 9:
w='[a-zA-Z0-9_\-]*'
This results in illegal Bash variable names. Back to the drawing board. Still a great function though.

@elderjeb

elderjeb commented Dec 4, 2017

Copy link
Copy Markdown

@SomeGuy54321 I have the same requirement, if you make that change to line 9, you can add these to the final sed:

sed 's/_/__/g' | sed 's/-/_/g'

So the convention becomes space = double underscore and dash = underscore.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment