Ale*_* N. 27 bash scripting properties
我正在考虑使用sed来读取.properties文件,但是想知道是否有一种更聪明的方法可以从bash脚本中做到这一点?
Dmi*_*mov 28
这可能是最简单的方法:grep + cut
# Usage: get_property FILE KEY
function get_property
{
grep "^$2=" "$1" | cut -d'=' -f2
}
Run Code Online (Sandbox Code Playgroud)
Jos*_*vis 16
上述解决方案将适用于基础知识.我不认为它们涵盖多行值.这是一个awk程序,它将从stdin解析Java属性并生成shell环境变量到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";
}
Run Code Online (Sandbox Code Playgroud)
如您所见,多行值使事情变得更加复杂.要查看shell中属性的值,只需在输出中获取:
cat myproperties.properties | awk -f readproperties.awk > temp.sh
source temp.sh
Run Code Online (Sandbox Code Playgroud)
变量的'.'代替'.',因此属性some.property将在shell中为some_property.
如果您有具有属性插值的ANT属性文件(例如'$ {foo.bar}'),那么我建议将Groovy与AntBuilder一起使用.
这是我关于这个话题的维基页面.
一种选择是编写一个简单的 Java 程序来为您执行此操作 - 然后在您的脚本中运行该 Java 程序。如果您只是从单个属性文件中读取属性,这可能看起来很愚蠢。但是,当您尝试从诸如CompositeConfiguration由属性文件支持的 Commons 配置之类的东西获取配置值时,它变得非常有用。有一段时间,我们采用了在 shell 脚本中实现我们需要的方法,以获得与从CompositeConfiguration. 然后我们清醒了,意识到我们应该让CompositeConfiguration我们为我们做工作!我不希望这是一个受欢迎的答案,但希望你觉得它有用。