读取Java的.properties从bash的文件 [英] Reading java .properties file from bash

查看:132
本文介绍了读取Java的.properties从bash的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用SED读取.properties文件,但不知道是否有一个更聪明的办法做到这一点从bash脚本?

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?

推荐答案

上述将为基本的工作方案。我不认为他们虽然涵盖多行的值。下面是一个awk程序,它将从标准输入解析Java的性能和生产shell环境变量到stdout:

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

该变量将有'_'在的地方'。',所以物业some.property将外壳是some_property。

The variables will have '_' in the place of '.', so the property some.property will be some_property in shell.

如果您有拥有财产性插值(例如$ {foo.bar}')ANT属性文件那么我建议使用Groovy与AntBuilder。

If you have ANT properties files that have property interpolation (e.g. '${foo.bar}') then I recommend using Groovy with AntBuilder.

下面是对这个题目我的wiki页面

这篇关于读取Java的.properties从bash的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆