【问题标题】:sed, awk to replace xml elementssed, awk 替换 xml 元素
【发布时间】:2017-09-06 20:24:42
【问题描述】:

我有一个 xml 文件,file.xml

如下:

<?xml version="1.0" encoding="UTF-8"?>

<bookstore>

<book category="cooking">
  <title lang="en">Everyday Italian</title>
  <author>Giada De Laurentiis</author>
  <year>2005</year>
  <price>30.00</price>
</book>

<book category="children">
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
</book>

<book category="web">
  <title lang="en">XQuery Kick Start</title>
  <author>James McGovern</author>
  <author>Per Bothner</author>
  <author>Kurt Cagle</author>
  <author>James Linn</author>
  <author>Vaidyanathan Nagarajan</author>
  <year>2003</year>
  <price>49.99</price>
</book>

<book category="web">
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>2003</year>
  <price>39.95</price>
</book>

</bookstore>

从中,我需要将 fileA.txt 中的所有值替换为 fileB.txt 中的值

fileA.txt 示例:

500
345
623
etc

要搜索的值

fileB.txt 示例:

550
350
700
etc

所以&lt;price&gt;500&lt;/price&gt; 应该变成&lt;price&gt;550&lt;/price&gt;

我可以多次运行以下命令,

sed -i 's/old/new/g' file.xml,

你能不能给我一个更聪明的方法,例如指定替换必须只发生在标签中,如果我需要用 600 替换 500,那么 5000 不会变成 6000?

也许首选 python 脚本?

就像在 cmets 中一样,你能告诉我一个 python 方法吗,因为我可能使用了错误的工具来完成这项任务?

【问题讨论】:

  • 使用可识别 XML 的工具。 Sedawk 不是适合这项工作的工具。
  • 您可以使用sed 's/\b500\b/600/g' file.xml 仅替换 500 而不是 5000。
  • 快速搜索返回这种东西:stackoverflow.com/q/6523886/2088135
  • 不错的文件样本。 xml 文件中没有一个匹配项。祝你好运。

标签: python xml awk sed


【解决方案1】:

sed 可能是错误的工具,但如果确定 file.xml 中不存在其他 fileA.txt 数字,但那些需要更改,这应该工作:

paste file[AB].txt | sed 's/^.*/s#\\b&/;s/.*$/&#g/;s/\t/\\b#/' | sed -f - file.xml

首先pastefileA.txtfileB.txt放在一起:

500 550
345 350
623 700
etc etc

然后sed 将其转换为未来的sed substitute 命令:

s#\b500\b#550#g
s#\b345\b#350#g
s#\b623\b#700#g
s#\betc\b#etc#g

然后将这些通过管道传送到运行这些命令的sed -f -

【讨论】:

    【解决方案2】:

    你可以用xmlstarlet 做类似的事情。例如,

    xmlstarlet ed -u //price[text()='30.00'] -v '32.00' bookstore.xml
    

    将在您的示例文件中将30.00 的价格替换为32.00 的价格。您可以按照 agc 的演示从文件构建命令行,但这会很繁重。

    【讨论】:

      猜你喜欢
      • 2019-04-30
      • 2017-09-19
      • 2016-10-29
      • 2013-05-30
      • 2014-02-05
      • 2010-11-23
      • 2011-01-23
      • 2020-10-29
      • 1970-01-01
      相关资源
      最近更新 更多