Last active
April 30, 2020 00:12
-
-
Save jaawerth/dad11b1cb3cbcdf8417d04cb23af1ffa to your computer and use it in GitHub Desktop.
This file contains 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 | |
# if args are passed, use first arg as file to process. otherwise assume STDIN | |
if [ $# -ge 1 -a -f "$1" ]; then | |
infile="$1"; shift; | |
else | |
infile="-" | |
fi | |
# here be my awk program! | |
IFS='' PROG=$(cat <<'EOAWK' | |
function wrap(x) { | |
if (length(x) > 0 && x ~ /^[0-9]?\.?[0-9]*$/) return x; | |
return sprintf("\"%s\"", x); | |
} | |
function json(data, k, txt, sep, i, out) { | |
out=""; | |
i=0; | |
if (!isarray(data)) return wrap(data) | |
out=out sprintf("{ ") | |
for (k in data) { | |
txt=isarray(data[k]) ? json(data[k]) : wrap(data[k]) | |
sep=(++i < length(data)) ? ", " : " "; | |
out=out sprintf("\"%s\": %s%s", k, txt, sep); | |
}; | |
out=out sprintf("}"); | |
return out; | |
} | |
BEGIN { FS="="; output=""; } | |
$0 ~ /^[:space:]*\[.+\][:space:]*$/ { | |
section=gensub(/^[:space:]*\[(.+)\][:space:]*$/, "\\1", 1) | |
} | |
$0 !~ /^#|^[:space:]*\[.+\][:space:]*$/ && length($1) > 0 { | |
if (length(section) > 0) { | |
data[section][$1]=$2 | |
} else { | |
data[$1]=$2 | |
} | |
} | |
END { | |
print json(data) | |
} | |
EOAWK | |
) | |
# run it! append any remaining arguments to awk | |
cat $infile | gawk $PROG "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment