bash - 如何计算bash中单词后的所有数字

标签 bash awk sed grep

我有这样的 xml 文件:

<?xml version="1.0" encoding="UTF-8"?>
<testsuites name="social_service_demo" time="0.583">
  <testsuite name="demo / generate_access_token" id="60ec54b9-d67b-4f51-a20d-9794c3a85269" tests="2" time="0.583">
    <error>
    </error>
    <testcase name="Token should be generated correctly, response is 200" time="0.583">
      <failure type="AssertionFailure">
        <![CDATA[Failed 1 times.]]>
      </failure>
    </testcase>
    <testcase name="Returned JSON should contain access_token field" time="0.583">
      <failure type="AssertionFailure">
        <![CDATA[Failed 1 times.]]>
      </failure>
    </testcase>
  </testsuite>
  <testsuite name="demo / get_most_commented_entities" id="12aa656d-a702-4fc6-878c-2e0fde08021e" tests="1" time="0">
    <error>
    </error>
    <testcase name="Response is 200" time="0">
      <failure type="AssertionFailure">
        <![CDATA[Failed 1 times.]]>
      </failure>
    </testcase>
  </testsuite>
</testsuites>

我需要计算 tests 之后的数字像这样排队: <testsuite name="demo / generate_access_token" id="60ec5" tests="2" time="0.583"> . 在这个例子中,我有两个这样的数字:2 和 1,所以我的输出应该是 3。如何在 Bash 中执行此操作? grep 可以吗?

最佳答案

不要使用 grepsed 和类似的工具来解析 XML/HTML 数据——它永远不会产生健壮和可扩展的结果。
使用适当的 XML/HTML 处理器,例如 xmlstarlet:

xmlstarlet sel -t -v 'sum(//testsuite[@tests]/@tests)' -n input.xml

输出:

3

关于bash - 如何计算bash中单词后的所有数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48990273/

相关文章:

bash - 根据单独文件中列出的值从文本文件中删除观察结果

Mysql函数返回系统结果

linux - 文本文件中特定行的转换

linux - 如何获取unix数据文件中每行的前n个字符

regex - Linux SED RegEx 替换,但保留通配符

linux - 尝试使用 grep 匹配同一行上的多个模式

php - 在linux中使用php创建txt文件

linux - 如何使用 upnpc 通过实时 UPNP 重定向使 Linux 上的虚拟机 (VM) 始终可访问

linux - 在两个引号 unix 中查找单词

正则表达式和 sed 在多行 block 中查找字符串 block ,直到它以空格结尾