brpaz
10/2/2015 - 6:26 PM

Parse YAML from bash with sed and awk.

Parse YAML from bash with sed and awk.

#!/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'
}

parse_yaml config.yml
development_adapter=("mysql2")
development_encoding=("utf8")
development_database=("my_database")
development_username=("root")
development_apt+=("somepackage")
development_apt+=("anotherpackage")
development:
  adapter: mysql2
  encoding: utf8
  database: my_database
  username: root
  password:
  apt:
    - somepackage
    - anotherpackage