Parsing variables from config file in Bash

2020-01-24 07:33发布

Having the following content in a file:

VARIABLE1="Value1"
VARIABLE2="Value2"
VARIABLE3="Value3"

I need a script that outputs the following:

Content of VARIABLE1 is Value1
Content of VARIABLE2 is Value2
Content of VARIABLE3 is Value3

Any ideas?

7条回答
ら.Afraid
2楼-- · 2020-01-24 08:22

given a config file as follows :-

[a]
b=C
d=E;rm t1
[b]
g=h

the following one-liner will parse and hold the values :-

CFG=path-to-file; for ini in `awk '/^\[/' $CFG`;do unset ARHG;declare -A ARHG;while read A B;do ARHG[$A]=$B;echo "in section $ini, $A is equal to"  ${ARHG["$A"]};done < <(awk -F'=' '/\[/ {x=0} x==1 && $0~/=/ && NF==2 {print $1, $2} $0==INI {x=1}' INI="$ini" $CFG);declare -p ARHG;echo;done;printf "end loop\n\n";declare -p ARHG

Now, let's break that down

CFG=path-to-file;
for ini in `awk '/^\[/' $CFG` # finds the SECTIONS (aka "ini")
do 
  unset ARHG # resets ARHG 
  declare -A ARHG # declares an associative array
  while read A B
  do
    ARHG[$A]=$B
    echo "in section $ini, $A is equal to"  ${ARHG["$A"]}
  done < <(awk -F'=' '/\[/ {x=0} x==1 && $0~/=/ && NF==2 {print $1, $2} $0==INI {x=1}' INI="$ini" $CFG)
  # the awk splits the file into sections, 
  # and returns pairs of values separated by "="
  declare -p ARHG # displays the current contents of ARHG
  echo
done
printf "end loop\n\n"
declare -p ARHG

This allows us to save values, without using eval or backtick. To be "really clean", we could remove [:space:] at the start and end of line, ignore "^#" lines, and remove spaces around the "equals" sign.

查看更多
登录 后发表回答