Skip to content

Instantly share code, notes, and snippets.

@jquinter
Last active April 15, 2018 12:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jquinter/6bdd14a8c6903dc76896e9278a37428e to your computer and use it in GitHub Desktop.
Save jquinter/6bdd14a8c6903dc76896e9278a37428e to your computer and use it in GitHub Desktop.
Parse YAML from bash with sed and awk.
development:
adapter: mysql2
encoding: utf8
database: my_database
username: root
password:
apt:
- somepackage
- anotherpackage
development_adapter=("mysql2")
development_encoding=("utf8")
development_database=("my_database")
development_username=("root")
development_apt+=("somepackage")
development_apt+=("anotherpackage")
#!/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'|tr -d '\015')"
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
@jquinter
Copy link
Author

I have included this minor change on line 14 of the original script:
|tr -d '\015'

so from this
fs="$(echo @|tr @ '\034')"

you end with this
fs="$(echo @|tr @ '\034'|tr -d '\015')"

This change allows to filter the damn carriage return from your lines, which messes up sometimes the processing of a yaml file.

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