I am trying to read a properties file from a shell script which contains a period (.) character like below:
# app.properties
db.uat.user=saple user
db.uat.passwd=secret
#/bin/sh
function pause(){
read -p "$*"
}
file="./app.properties"
if [ -f "$file" ]
then
echo "$file found."
. $file
echo "User Id " $db.uat.user
echo "user password =" $db.uat.passwd
else
echo "$file not found."
fi
I have tried to parse the file after sourcing the file but it is not working since the keys contains the "." character and there are spaces in that value also.
My properties file always resides in the same directory of the script or somewhere in /usr/share/doc
As (Bourne) shell variables cannot contain dots you can replace them by underscores. Read every line, translate . in the key to _ and evaluate.
#/bin/sh
file="./app.properties"
if [ -f "$file" ]
then
echo "$file found."
while IFS='=' read -r key value
do
key=$(echo $key | tr '.' '_')
eval ${key}=\${value}
done < "$file"
echo "User Id = " ${db_uat_user}
echo "user password = " ${db_uat_passwd}
else
echo "$file not found."
fi
Note that the above only translates . to _, if you have a more complex format you may want to use additional translations. I recently had to parse a full Ant properties file with lots of nasty characters, and there I had to use:
key=$(echo $key | tr .-/ _ | tr -cd 'A-Za-z0-9_')