【问题标题】:I need to extract following data from xml file in bash mac:我需要从 bash mac 中的 xml 文件中提取以下数据:
【发布时间】:2019-02-23 23:33:13
【问题描述】:

我需要从以下获取数字和文件名的值:

 <title><num>4.</num></title>

                    <header>Kurztitel für Kolumnentitel</header>

                    <bibl>Bibliographische Angaben zu den folgenden Schriftstücken</bibl>

                    <xmlfile name="1790-Verhandeling"/>

因此,我应该使用 mac bash 终端获得类似的结果:

1790-Verhandeling,4

(1790-Verhandeling 来自 "xmlfilename=" 和 4 来自 "num")

我想过使用这样的东西:

grep '<num>' myfile.xml | sed "s@.*<num>\(.*\)</num>.*@\1@"

但我不知道如何获取所需的其余信息

提前感谢您的帮助!

【问题讨论】:

  • 我建议使用 XML/HTML 解析器 (xmlstarlet, xmllint ...)。
  • 您的示例不是有效的 XML。

标签: xml bash macos terminal tags


【解决方案1】:

简单的解决方案:

grep -oP '<num>\K(\d+)|<xmlfile name="\K(.*?)(?=")' < myfile.xml | tac | paste -d',' - -

希腊语: -o 仅匹配 -P 启用 Perl 正则表达式 \K 从它开始匹配 (?=...) 捕获的匹配必须后跟括号内的任何内容,但该部分未被捕获

Tac 匹配行的倒序

粘贴(在一行中粘贴多行): -d 是一个分隔符,在我们的例子中,我们选择了逗号 -- 从两行到时间做单行

【讨论】:

  • 非常感谢您的快速回答,但我在 Mac 终端上得到以下结果:-bash: tac: command not found 用法:grep [-abcDEFGHhIiJLlmnOoqRSsUVvwxZ] [-A num] [ -B num] [-C[num]] [-e 模式] [-f 文件] [--binary-files=value] [--color=when] [--context[=num]] [--directories =action] [--label] [--line-buffered] [--null] [pattern] [file ...]
  • 对于基本问题,我很抱歉,但我对 Grep 和 Perl 很陌生 ;)
  • @AndresFischer:使用 GNU grep 或更好的 XML/HTML 解析器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-26
  • 2016-09-19
  • 1970-01-01
  • 1970-01-01
  • 2013-07-28
  • 2013-03-20
  • 1970-01-01
相关资源
最近更新 更多