【问题标题】:Bash script Insert file to xml file after specific elementBash脚本在特定元素之后将文件插入到xml文件
【发布时间】:2014-03-28 15:03:20
【问题描述】:

我有一个以下格式的 XML 文件:

 <Country name=England>
  <City name_city=London>
  some thing here
  </City>
  <City name_city=Manchester>
  some thing here
  </City>
  <City name_city=Liverpool>
  some thing here
  </City>
  Many other elements like these ones.
</Country>

还有一个像这样的文件:

  <City name_city=Hull>
  some thing here
  </City>

使用 bash 脚本,如何将后面文件的内容插入到第一个元素之后的第一个文件中

  <City name_city=Manchester>
  some thing here
  </City>

我期待使用 SED 或 AWK 来解决问题。

感谢您的帮助。

【问题讨论】:

  • 使用 Sed 或 Awk 修改 XML 不是一个好主意。 Sed 和 Awk 用于面向行的数据。 XML 不是面向行的数据。您必须限制您的 XML,这迟早会破坏您的应用程序。您应该考虑基于 XSLT 的解决方案。试试Saxon

标签: xml bash sed awk


【解决方案1】:

从不推荐使用sedawk 解析xml。有更好的工具了三个。如果这是一个学习练习,那么您可以执行以下操作,但就像我说的,使用正确的 xml 解析器。

awk '
/City name_city=Manchester>/ { flag = 1 } 
flag && /<\/City>/ { 
    print $0; 
    while((getline line < "file2") > 0) { 
        print line; 
    }
    flag=0
    next
}1' file1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多