I have a properties file test.properties
and it contents are as follows:
x.T1 = 125
y.T2 = 256
z.T3 = 351
How can I assign the value of y.T2
(256
) to some variable within shell script and echo this value?
I have a properties file test.properties
and it contents are as follows:
x.T1 = 125
y.T2 = 256
z.T3 = 351
How can I assign the value of y.T2
(256
) to some variable within shell script and echo this value?
Check this, will help exactly:
expVal=`cat test.properties | grep "y.T2" | cut -d'=' -f2`
You want to use read
in a loop in your script. While you can source
a file, it doesn't work if there are spaces surrounding the =
sign. Here is a way to handle reading the file:
#!/bin/sh
# test for required input filename
if [ ! -r "$1" ]; then
printf "error: insufficient input or file not readable. Usage: %s property_file\n" "$0"
exit 1
fi
# read each line into 3 variables 'name, es, value`
# (the es is just a junk variable to read the equal sign)
# test if '$name=y.T2' if so use '$value'
while read -r name es value; do
if [ "$name" == "y.T2" ]; then
myvalue="$value"
fi
done < "$1"
printf "\n myvalue = %s\n\n" "$myvalue"
Output
$ sh read_prop.sh test.properties
myvalue = 256
I know this is an old question, but I just came across this and if I understand correctly, the question is to get value for a specific key from the properties file. Why not just use grep to find the key and awk to get the value?
Use grep and awk to extract the value from test.properties
export yT2=$(grep -iR "^y.T2" test.properties | awk -F "=" '{print $2}')
echo y.T2=$yT2
This value will contain space if there's one after the '='. Trim the leading whitespace
yT2="${yT2#"${yT2%%[![:space:]]*}"}"
Reference for trim: How to trim whitespace from a Bash variable?. Explanation available at reference link.