【问题标题】:Updating web.xml using shell script to change the param-value使用 shell 脚本更新 web.xml 以更改参数值
【发布时间】:2013-11-21 20:17:33
【问题描述】:

我在 web.xml 中有以下条目

<context-param>
  <param-name>oracle.adf.view.rich.automation.ENABLED</param-name>
  <param-value>false</param-value>
</context-param>

我正在使用 shell 脚本进行一些重新打包工作,并且只想将给定参数名称的值从“false”更改为“true”。我怎样才能使用 sed/awk 命令来做到这一点?请注意,有多个参数名称和参数值条目的“假”值不应随之更改。

【问题讨论】:

    标签: xml bash shell sed awk


    【解决方案1】:
    awk -v tgt='oracle.adf.view.rich.automation.ENABLED' '
        found { sub(/false/,"true"); found=0 }
        { found = index($0,"<param-name>" tgt "</param-name>" }
    ' file
    

    【讨论】:

    • 出现语法错误 - awk: found { sub(/false/,"true"); found=0 } { found = index($0,"" tgt "" } ^ 语法错误
    • 好的,所以修复语法错误。我敢肯定,如果您花几分钟的时间思考一下,您就会明白问题出在哪里。它只是另一种编程语言,并不神奇。
    【解决方案2】:

    Don't parse XML with regex !

    使用 & (一个合适的XML解析器):

     xmlstarlet edit -L -u "/context-param/param-value" -v 'true' file.xml
    

    为了匹配第N个元素,你可以稍微调整一下(从1开始):

     xmlstarlet edit -L -u "/context-param[10]/param-value[5]" -v 'true' file.xml
    

    【讨论】:

    • 看起来我需要为此安装 xmlstartlet,这对我来说是不可能的。此外,它使用的计数可能会在未来发生变化,这是一个风险..
    • 如果xmlstarlet没有安装,可能perl是?
    【解决方案3】:
    sed "/<context-param>/,/<\/context-param>/ {
       /<context-param>/ h
       /<context-param>/ !H
       /<\/context-param>/ {
         x;s/<param-name>oracle.adf.view.rich.automation.ENABLED<\/param-name>/&/
         t chg
         b
    :chg
         s/<param-value>false</<param-value>true</
         }" web.xml
    

    处理部分上下文参数,加载缓冲区,检查参数名称是否正确,如果是则将 false 更改为 true

    【讨论】: