【问题标题】:Can't change my Java .properties file with shell script无法使用 shell 脚本更改我的 Java .properties 文件
【发布时间】:2016-04-12 14:20:51
【问题描述】:

我正在寻找一种方法来执行可以更改我的 Java .properties 文件的 shell 脚本

.properties 文件非常简单:

WBURL=http://google.com

我希望该脚本更改 WBURL 的地址

我一直在网上寻找,但我迷路了,一切都很艰难...... 有人能帮帮我吗?

谢谢

【问题讨论】:

  • 你有什么操作系统?
  • 它在 linux (Xubuntu) 上
  • 如果shell脚本太难了(通常情况下不应该这么简单)你不能写一个简短的Java工具吗?
  • 我必须编写一个 shell 脚本,因为它必须在 Jenkins 构建之前运行,而且更容易(理论上 ^^)

标签: java shell properties


【解决方案1】:

你可以使用awk:

awk -v val="http://localhost" 'BEGIN{FS=OFS="="} $1 == "WBURL"{$2=val} 1' file

WBURL=http://localhost

或者使用sed:

val="http://localhost"

sed -i -E "s~(WBURL=).*~\1$val~" file

cat file
WBURL=http://localhost

【讨论】:

  • 感谢您的帮助,使用 sed 解决方案时出现错误:\1 未在 RE 中定义
  • 您是否按照我在这里的建议使用了-E 选项?
  • 是的,我这样做:val="localhost" // sed -i -E "s~(WBURL=).*~\1$val~" config.properties // // cat config.properties // WBURL=localhost ( // 只是为了在评论中看得更清楚)
  • 使用 awk 保存对文件的更改:awk -v val="http://localhost" 'BEGIN{FS=OFS="="} $1 == "WBURL"{$2=val} 1' file > file.tmp && mv file.tmp file
  • 我的错,我以为我已经这样做了。再次感谢你:)
【解决方案2】:

由于您说这是属性文件中的唯一条目,因此从头开始重新创建它可能是最简单的:

echo WBURL=http://localhost >.properties

【讨论】:

    猜你喜欢
    • 2012-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-03
    相关资源
    最近更新 更多