Last active
December 22, 2015 00:09
-
-
Save unakatsuo/6387005 to your computer and use it in GitHub Desktop.
AWK script that converts YAML text to "/" delimitered format. Help shell script to retrieve complex YAML document.
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
function ydump() { | |
# nm: namespace array | |
# lv: namespace level | |
# cidt: current indent depth | |
# lidt: last indent depth | |
# ac: array counter | |
awk -v lv=1 -v ac=0 -v cidt=1 -v lidt=1 'BEGIN{ nm[1]=""; } | |
function path_join(ary, _i,_r,_s) { _r=""; for(_i = 1; _i <= lv; _i++){ _r = _r "/" ary[_i];}; sub("/$", "", _r); sub("^/+", "", _r); return _r; } | |
# get the current indent depth. | |
{ match($0, /[^ ]+/); cidt=RSTART;} | |
$1 == "-" { cidt = cidt + 2; } | |
# indent level calculation for level down case. | |
cidt < lidt { | |
for(_i=1; _i <= ((lidt - cidt) / 2); _i++){ | |
lv--; | |
if ( nm[lv] ~ /^[[:digit:]]+$/ ){ lv--; ac=nm[lv]; } | |
} | |
} | |
# indent level calculation for level up case. | |
cidt > lidt { lv++; } | |
cidt > lidt && $1 == "-" { ac=0; nm[lv]=ac; lv++; } | |
cidt == lidt && $1 == "-" { ac++; nm[lv-1]=ac; } | |
$1 ~ /^:?[[:alnum:]_]+:/ { nm[lv]=$1; } | |
$1 ~ /^:?[[:alnum:]_]+:/ && NF == 1 { print path_join(nm) "="; } | |
$1 ~ /^:?[[:alnum:]_]+:/ && NF == 2 { print path_join(nm) "=" $2; } | |
# | |
$1 == "-" && $2 ~ /^:?[[:alnum:]_]+:/ { nm[lv]=$2; } | |
$1 == "-" && $2 !~ /^:?[[:alnum:]_]+:/ && NF == 2 { print path_join(nm) "=" $2; } | |
$1 == "-" && $2 ~ /^:?[[:alnum:]_]+:/ && NF == 3 { print path_join(nm) "=" $3; } | |
{ lidt=cidt; }' | |
} |
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
$ cat <<EOF | ydump | |
--- | |
:xxxx: | |
:yyyy: 2 | |
:zzzz: 3 | |
:oooo: | |
- a | |
- b | |
:pppp: | |
- c | |
- d | |
:qqqq: | |
- :a: 1 | |
:b: 2 | |
- :a: 3 | |
:b: 4 | |
EOF | |
:xxxx:/:yyyy:=2 | |
:xxxx:/:zzzz:=3 | |
:oooo:/0=a | |
:oooo:/1=b | |
:pppp:/0=c | |
:pppp:/1=d | |
:qqqq:/0/:a:=1 | |
:qqqq:/0/:b:=2 | |
:qqqq:/1/:a:=3 | |
:qqqq:/1/:b:=4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment