【问题标题】:how can I change the value in xml using bash如何使用 bash 更改 xml 中的值
【发布时间】:2016-03-08 09:16:07
【问题描述】:

如何使用 bash 更改 xml 中的值

<resources> <string name="app_name">Keep Accounts</string> <string name="login">"login"</string> <string name="login_password">"password:"</string> <string name="login_account_hint">input to login</string> <string name="login_password_hint">input your password</string> <string name="login_fail">login failed</string> </resources>

例如我想将值“Keep Accounts”更改为“Keep Accounts 2”。“app_name”可能不仅是“Keep Accounts”,还可以是其他值,比如 XXX,但“app_name”是当然,我希望输出是:

<resources> <string name="app_name">XXX 2</string> <string name="login">"login"</string> <string name="login_password">"password:"</string> <string name="login_account_hint">input to login</string> <string name="login_password_hint">input your password</string> <string name="login_fail">login failed</string> </resources>

【问题讨论】:

  • 我怀疑您需要向我们展示更多背景信息;目前,sed 's/Keep Accounts/&amp; 2/' file.xml 可以解决您的问题,但它不适合这项工作,并且可能不适用于您的真实数据。
  • 项目可能很多,所以应该通过“app_name”选择,然后更改值。
  • edit您的问题向我们展示一个更完整的示例以及所需的输出。
  • 我更新问题:) 希望可以理解

标签: xml bash


【解决方案1】:

使用 XML 感知工具。我会在xsh

open file.xml ;
insert text " 2" into /resources/string ;
save :b ;

【讨论】:

  • 看起来不错的工具!
【解决方案2】:
sed -i 's/<string name=\"app_name\">.*<\/string>/<string name=\"app_name\">NewName<\/string>/g' xml_filename.xml

替换任何 'app_name' 的单行 sed (bash) 解决方案

使用 sed -i 替换相关文件的内容

我假设您在一个名为 xml_filename.xml 的文件中包含 xml 内容,但根据需要进行更改

【讨论】:

  • -i.bu 没问题。但我想要基于旧名称的新名称。例如旧名称为“Hello”,新名称应为“Hello(new)”
【解决方案3】:

如果你安装了python-pip,你可以用pip install yq安装xq,然后试试这个(我已经测试过了):

xmldoc=$(cat <<'EOF'
<resources>
    <string name="app_name">Keep Accounts</string>
    <string name="login">"login"</string>
    <string name="login_password">"password:"</string>
    <string name="login_account_hint">input to login</string>
    <string name="login_password_hint">input your password</string>
    <string name="login_fail">login failed</string>
</resources>
EOF
)
echo "$xmldoc" | xq '.resources.string = ([.resources.string[]|select(."#text" == "Keep Accounts") ."#text" = "Keep Accounts 2"])' -x

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多