How to extract values from a java properties files in a bash/shell script

Let's say you have a java properties (sample.prop ) file that contains this :

ORACLE_HOST=myhost.us.oracle.com
MW_HOME=/scratch/codrguy/sandbox
DB_HOST=dbhost.us.oracle.com
Now, if we want to extract values from this properties file and use it in a shell/bash script for let's say an automation task, how do we go about that.

There are 3 parts to this task: 1) Getting the line that contains the value we want 2) extract the value from that line 3) store it in a variable to be used later in the script

To do part 1 we can simply grep for the value of the property we need :
For example :
grep ORACLE_HOST sample.prop
this returns
ORACLE_HOST=myhost.us.oracle.com

To do part 2 we pipe the output of part 1 into awk for extraction of the value we need
grep ORACLE_HOST sample.prop |  awk -F= '{print $2}'
this returns
myhost.us.oracle.com

the -F option of awk sets the delimiter to be '=' and then we print the second record which is what we need

Finally to store this value in a variable we do :

my_value=$(grep ORACLE_HOST sample.prop |  awk -F= '{print $2}')


1 comment:

  1. my_value=$(awk -F= '$1=="ORACLE_HOST" {print $2}' sample.prop)

    ReplyDelete