【问题标题】:How to modify xml config file with grep and sed?如何使用 grep 和 sed 修改 xml 配置文件?
【发布时间】:2021-04-24 15:12:45
【问题描述】:

在我的 Linux 培训中,我有一个练习要求替换 config.xml 文件中的语句。

我需要替换语句:

<app-connector port="${APP_CONNECTOR_PORT}" address="192.168.0.254"

通过这个:

<app-connector port="${APP_CONNECTOR_PORT}" address="0.0.0.0"

我已经开始grepconfig.xml 文件中的所有现有语句,但它不起作用:

Cat config.xml | grep '<app-connector port="${APP_SYSTEM_CONNECTOR_PORT}" address="192.168.0.254"'

还有

Cat config.xml | grep -F '<app-connector port="${APP_SYSTEM_CONNECTOR_PORT}" address="192.168.0.254"'

你能告诉我如何在所有config.xml文件中找到这个语句吗?

如何替换为:

<app-connector port="${APP_CONNECTOR_PORT}" address="0.0.0.0"

【问题讨论】:

  • 使用 XML 特定的命令行工具,例如 xmlstarlet,因为 sed , awk, grep, and so on leads to undesired results。例如,尝试以下 xmlstarlet 命令:xml ed -L -u "//app-connector[@port='\${APP_CONNECTOR_PORT}']/@address[. = '192.168.0.254']" -v "0.0.0.0" /some/path/to/config.xml - 此命令替换 192.168.0.254 的所有 address 属性值,如果它们关联的 xml 节点是 &lt;app-connector&gt; 并且它也有一个 port ${APP_CONNECTOR_PORT} 的属性值。

标签: xml bash sed grep config-files


【解决方案1】:
sed -i '/<app-connector port="${APP_CONNECTOR_PORT}" address="192.168.0.254"$/s/192.168.0.254/0.0.0.0/' file

使用 sed,使用 /..../ 搜索有问题的行,然后将“192.168.0.254”替换为“0.0.0.0”

【讨论】:

  • 抱歉没用,你能帮帮我吗
  • 运行后的行是什么样子的?
  • 什么也没发生。我在单机上尝试了 sed 's/app-connector port="${APP_CONNECTOR_PORT}" address="192.168.0.254"/app-connector port="${APP_CONNECTOR_PORT}" address="0.0.0.0" config.xml错误是 'char 15: unterminated `s' command
  • 您在 sed 命令的末尾缺少 / 和 '。只需复制并粘贴解决方案中的命令即可。
猜你喜欢
  • 2011-06-21
  • 1970-01-01
  • 2014-02-02
  • 2012-07-11
  • 1970-01-01
  • 1970-01-01
  • 2014-05-15
  • 2012-10-10
  • 1970-01-01
相关资源
最近更新 更多