Skip to content

Instantly share code, notes, and snippets.

@paulc
Created January 31, 2021 19:31
Show Gist options
  • Save paulc/fdb3e2056f47d5abe64e4bc1dd2e0073 to your computer and use it in GitHub Desktop.
Save paulc/fdb3e2056f47d5abe64e4bc1dd2e0073 to your computer and use it in GitHub Desktop.
yaml-get
#!/bin/sh
# XXX THIS DOESN'T WORK XXX
awk -v key="${1?Usage: yaml_get_section <section>}" -v debug=${DEBUG-0} '
BEGIN {
found = 0
multiline = 0
}
{ if (debug != "0") print "found=" found " multiline=" multiline " >>" $0 }
# Skip whitespace
/^[[:space:]]*$/ {
next
}
# Skip comments
/^[[:space:]]*#/ {
next
}
# Find key
$0 ~ "^" key ":" {
# Clear continuation flag
if (multiline == 1) {
printf("\n")
multiline = 0
}
# Check for inline value
if (NF>1) {
# Inline value
if (substr($0,length($0),1) == "\\") {
# Trailing \
sub("^.*:[[:space:]]*","")
sub(".$","")
found = 1
printf($0)
} else {
# Remove leading key value
sub("^.*:[[:space:]]*","")
print
}
} else {
# Multi-line value
found = 1
}
next
}
# New key - clear search
/^[[:alnum:]]/ {
found = 0
# Clear continuation flag
if (multiline == 1) {
printf("\n")
multiline = 0
}
}
# New value
found == 1 && /^[[:space:]]*-[[:space:]]*/ {
if (multiline == 1) {
printf("\n")
multiline = 0
}
sub("^[[:space:]]*-[[:space:]]*","")
printf($0)
multiline = 1
next
}
# Continuation
found == 1 && /^[[:space:]]+/ {
sub("^[[:space:]]*","")
printf(" %s",$0)
}
'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment