I have a .config
file, which has data like:
category1 {
Key1="value1"
Key2="value2"
}
category2 {
Key1="value1"
Key2="value2"
}
How do I read these values in bash?
I want to access these values in my bash script.
CodePudding user response:
This is not json, so I am guessing you want to export environment variables to current shell. Then, assuming your file is 'some-config.conf' AND it is not nested crazy or anything:
shopt -s extglob
while read -r; do
#$REPLY is the default variable, assign it as you wish
if [[ "${REPLY}" =~ [{}] ]]
then
#ignore or use '!' within if test
:
else
#process the line but remove leading spaces first
declare -x "${REPLY## ([ ])}"
fi
#While reading line by line, ignore empty lines by 'grep -v'
done < <(cat some-config.conf | grep -Ev "^\s*$" )
#at this point you can do `echo ${Key1}`
if you want to export them to current shell, save it as 'parse.sh' and call:
. parse.sh
CodePudding user response:
Based on your sample input, awk
and it's matching operator ~
can extract the value of a key:
$ key="Key1"
$ awk -F= -v k=$key '$0 ~ k {print $NF}' config
"value1"