简体   繁体   中英

shell script to read property in an array from property file

conf.properties file have contents like this:

src1=abc
dest1=xyz

src2=123
dest2=456

...

The below shell script is accessing the src and dest properties from conf.properties file.

. /tmp/conf.properties

echo "$src1"
echo "$dest1"

echo "$src2"
echo "$dest2"

Now, there could be any number of src and dest properties in the file.

How to write a code to read all the src and dest from the property file into an array.

You can read and put them separately in two variables. Read the file line by line keep on appending the src thing in srcVal , seperated by space.

set -A srcArrVar -- $srcVal set -A destArrVar -- $destVal Or you can use associate arry like below

typeset -A srcArray
srcArray[src1]="abc"
srcArray[dest1]="xyz"

Yes you will need to parse the it .. I can immediately think of one way as below

grep "src" filename > srcFile
grep "dest" filename > destFile
sort srcFile > sortedSrcFile
sort destFile > sorteddestFile
srcVal=`cut -d"=" -f2 sortedSrcFile`
destVal=`cut -d"=" -f2 sorteddestFile`
set -A srcArrVar -- $srcVal
set -A destArrVar -- $destVal

There can be more elegant way of doing above thing by using sed/awk... and I have assumed that you have no missing values the series is continuous src1,src2... similarly dest1,dest2,dest3....

Created my own logic after getting clue from Ajay's Answer:

filename=/tmp/conf.properties

srcArr=($(grep "src" $filename)) 
destArr=($(grep "dest" $filename))

len=${#srcArr[@]}

for (( i=0; i<${len}; i++ ))
do
    srcVal=$(cut -d"=" -f2 <<< ${srcArr[i]})
    destVal=$(cut -d"=" -f2 <<< ${destArr[i]})

...

done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM