Last active
November 28, 2017 21:36
-
-
Save richtr/3dfb5f609bbf7dd36b7681ed053e238b to your computer and use it in GitHub Desktop.
Parse YAML from bash with sed and awk.
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
development: | |
adapter: mysql2 | |
encoding: utf8 | |
database: my_database | |
username: root | |
password: | |
apt: | |
- somepackage | |
- anotherpackage |
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 | |
YAML_INPUT_FILE="./config.yml" | |
eval "$(./yaml.sh ${YAML_INPUT_FILE} optional_prefix_)" | |
# Obtain parse_yml variables as follows: | |
echo "${optional_prefix_development_adapter}" | |
echo "${optional_prefix_development_apt[@]}" |
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 | |
# | |
# vim: set ft=sh: | |
# | |
# Based on https://gist.github.com/pkuczynski/8665367 | |
parse_yaml() { | |
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; | |
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); | |
} | |
}' | sed 's/_=/+=/g' | |
} | |
if [ ! -e "${1}" ]; then | |
exit 0; | |
fi | |
parse_yaml ${@} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment