我具有下面的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)将获取第二个数字值?
答案 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中完成完整提取。