Skip to content

Instantly share code, notes, and snippets.

@mbasaglia
Last active August 29, 2015 14:07
Show Gist options
  • Save mbasaglia/d37a3aef3813dae39938 to your computer and use it in GitHub Desktop.
Save mbasaglia/d37a3aef3813dae39938 to your computer and use it in GitHub Desktop.
shell script to read some config-looking data
#!/bin/bash
function read_config()
{
if [ -z "$2" ]
then
read -r -d '' $1
else
local input=""
for inp in "${@:2}"
do
input="$input
$inp"
done
eval "$1=\"$input\""
fi
}
function escape_regex()
{
echo "${@}" | sed -r -e 's/([.(){}[\]+?$^\\*])/\\\1/g'
}
function config_get_key()
{
grep -Eo -e "^\s*([^\"']\S*|\"[^\"]+\"|'[^']+')\s*[:=]" | sed -r -e "s/^\s*(\"|')?//" -e "s/(\"|')?\s*[:=]$//"
}
function config_get_value()
{
sed -r -e "s/^\s*([^\"']\S*|\"[^\"]+\"|'[^']+)\s*[:=]\s*//" -e "s/,$//" -e "s/^(\"|')//" -e "s/(\"|')$//"
}
function config_get()
{
local search=$(escape_regex "$2")
echo "$1" | grep -E -e "^\s*($search|(\"|')$search\2)\s*[:=]" | config_get_value
}
function config_foreach()
{
echo "$1" | while read line
do
key=$(echo "$line" | config_get_key)
value=$(echo "$line" | config_get_value "$key")
echo "@$key@$value@"
done
}
read_config jsonish <<CONFIG
foo: bar,
"hello": "world"
lol = wtf hello: lol
CONFIG
#read_config jsonish "foo: bar," "lol: wtf"
echo $jsonish
config_get "$jsonish" foo
config_get "$jsonish" hello
config_get "$jsonish" lol
echo
config_foreach "$jsonish"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment