I am thinking of using sed for reading .properties file, but was wondering if there is a smarter way to do that from bash script?
The Properties file can be used in Java to externalize the configuration and to store the key-value pairs. The Properties. load() method of Properties class is convenient to load . properties file in the form of key-value pairs.
This would probably be the easiest way: grep + cut
# Usage: get_property FILE KEY function get_property {     grep "^$2=" "$1" | cut -d'=' -f2 } 
                        The solutions mentioned above will work for the basics. I don't think they cover multi-line values though. Here is an awk program that will parse Java properties from stdin and produce shell environment variables to stdout:
BEGIN {     FS="=";     print "# BEGIN";     n="";     v="";     c=0; # Not a line continuation. } /^\#/ { # The line is a comment.  Breaks line continuation.     c=0;     next; } /\\$/ && (c==0) && (NF>=2) { # Name value pair with a line continuation...     e=index($0,"=");     n=substr($0,1,e-1);     v=substr($0,e+1,length($0) - e - 1);    # Trim off the backslash.     c=1;                                    # Line continuation mode.     next; } /^[^\\]+\\$/ && (c==1) { # Line continuation.  Accumulate the value.     v= "" v substr($0,1,length($0)-1);     next; } ((c==1) || (NF>=2)) && !/^[^\\]+\\$/ { # End of line continuation, or a single line name/value pair     if (c==0) {  # Single line name/value pair         e=index($0,"=");         n=substr($0,1,e-1);         v=substr($0,e+1,length($0) - e);     } else { # Line continuation mode - last line of the value.         c=0; # Turn off line continuation mode.         v= "" v $0;     }     # Make sure the name is a legal shell variable name     gsub(/[^A-Za-z0-9_]/,"_",n);     # Remove newlines from the value.     gsub(/[\n\r]/,"",v);     print n "=\"" v "\"";     n = "";     v = ""; } END {     print "# END"; }   As you can see, multi-line values make things more complex. To see the values of the properties in shell, just source in the output:
cat myproperties.properties | awk -f readproperties.awk > temp.sh source temp.sh   The variables will have '_' in the place of '.', so the property some.property will be some_property in shell.
If you have ANT properties files that have property interpolation (e.g. '${foo.bar}') then I recommend using Groovy with AntBuilder.
Here is my wiki page on this very topic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With