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



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

输入(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(将获取第二个数值?

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

<<<"$getTotalCount" jq -r '.healthReport[0].description' | awk -F'[^0-9,]+' '{ print $3 }'
使用
  • <<<将变量的内容传递给jq(如果您的 shell 不支持此功能,您可以按原样使用echo|(
  • 使用jq -r输出"原始"值,删除引号。
  • 使用-F'[^0-9,]+'将字段分隔符设置为非数字 (0-9( 或逗号的任何内容
  • 打印第三个字段,即所需的数字。

这就是字段最终看起来尴尬的样子:

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 }')

您可以保留原始消息中的空格。

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

这将剥离任何内容,直到"测试"之后的任何内容,并仅保留数字。

旁注: JQ有很多字符串内置函数。您可以使用正则表达式在 jq 中完成完全提取。

最新更新