如何使用Shell脚本从字符串获取第二个数值

时间:2019-10-04 08:17:20

标签: shell unix

我具有下面的String格式,我只想从下面的字符串中获取第二个数字值。

输入(jq的输出):

"Test Result: 21 tests failing out of a total of 5,670 tests."

预期输出:

5,670

我使用了以下命令,但返回的所有数字值都无法获取第二个。

echo "$getTotalCount" | jq '.healthReport[0].description' | sed 's/"//g' | sed 's/[^0-9]*//g'

获得以下输出:

215670

是否有可能获得像基于索引的值[0](结果= 21)将获取第一个数字值,[1](结果= 5670)将获取第二个数字值?

2 个答案:

答案 0 :(得分:1)

您可以将awk与自定义字段分隔符一起使用来提取数字:

<<<"$getTotalCount" jq -r '.healthReport[0].description' | awk -F'[^0-9,]+' '{ print $3 }'
  • 使用jq将变量的内容传递到<<<(如果您的外壳不支持此操作,则可以照常使用echo|)< / li>
  • 使用jq -r输出“原始”值,删除引号。
  • 使用-F'[^0-9,]+'将字段分隔符设置为非数字(0-9)或逗号的任何内容
  • 打印第三个字段,即您想要的数字。

这是最终看起来像awk的字段:

Test Result: 21 tests failing out of a total of 5,670 tests.
^ $1 (empty)
^-----------^ field separator
             ^^ $2
               ^-------------------------------^ field separator
                                                ^---^ $3

要将输出保存到变量,只需使用:

num_tests=$(<<<"$getTotalCount" jq -r '.healthReport[0].description' | awk -F'[^0-9,]+' '{ print $3 }')

答案 1 :(得分:0)

您可以在原始邮件中保留空格。

echo "$getTotalCount" | jq '.healthReport[0].description' | sed -e 's/^.* of //' -e 's/ tests.*//' -e 's/[^0-9]//g'

这将剥离“'”之前的所有内容,“测试”之后的所有内容,并且仅保留数字。

旁注: jq具有很多字符串内置功能。您也许可以使用正则表达式在jq中完成完整提取。