【问题标题】:Sed command to replace string that contains / and " [duplicate]用于替换包含 / 和 " 的字符串的 Sed 命令 [重复]
【发布时间】:2018-03-17 05:06:23
【问题描述】:

我有一个需求,我需要读取 XML 文件并替换包含 /" 的标签并将其另存为新文件。

原始标签格式:

<CollateralReportDocument xmlns="http://schemas.foo.com/sII/CollateralReportDocument/1.0">

新文件的标签应为:

<CollateralReportDocument>

我尝试过使用

Sed -i 's/<CollateralReportDocument xmlns="http://schemas.foo.com/sII/CollateralReportDocument/1.0">
/ <CollateralReportDocument>/g' filename.xml 

...但它不起作用。你能帮我解决这个问题吗?

【问题讨论】:

  • 修复正在读取文件的代码以支持命名空间是更好的做法。 XML 命名空间的存在是有原因的——它们是单个文档如何/为什么可以具有不同类型的(元)数据,并且设计这些模式的人不需要在有人可以组合之前协调一组名称这些模式在单个文档中。
  • 即使您确实想将 Collat​​eralReportDocument/1.0 命名空间中的所有内容都转换为默认命名空间,最好使用 XSLT 样式表,这样它就会知道如果您有 xmlns:crd="http://schemas.foo.com/sII/CollateralReportDocument/1.0"在您文档中的其他位置(或相同的未来版本)中,需要将文档的所有部分中的 crd:bah 更改为 bah 在树中发生定义的点下。

标签: bash shell unix sed


【解决方案1】:

您使用/ 作为分隔符,但您的字符串中也有一些/ 可以替换。

您应该改用# 作为分隔符。

Linux:

sed -i 's#<CollateralReportDocument xmlns="http://schemas.foo.com/sII/CollateralReportDocument/1.0">#<CollateralReportDocument>#g' filename.xml

ma​​cOS:

sed -i '' 's#<CollateralReportDocument xmlns="http://schemas.foo.com/sII/CollateralReportDocument/1.0">#<CollateralReportDocument>#g' filename.xml

【讨论】:

  • 命令工作没有任何错误,但 xml 文件仍然有旧标签,这是 Spark 的要求,我无法在根标签处读取此文件,因为结束标签是
  • @user2315840 奇怪...它适用于 macOS 和 Manjaro。您正在开发什么操作系统/发行版?
猜你喜欢
  • 2012-05-05
  • 2023-03-20
  • 2017-12-03
  • 1970-01-01
  • 2017-11-04
  • 1970-01-01
  • 1970-01-01
  • 2020-09-07
  • 2014-03-30
相关资源
最近更新 更多