如何使用shell脚本从字符串中获取第二个数值
我有下面的字符串格式,我只想从下面的字符串中得到第二个数值 输入(jq的输出):如何使用shell脚本从字符串中获取第二个数值,shell,unix,Shell,Unix,我有下面的字符串格式,我只想从下面的字符串中得到第二个数值 输入(jq的输出): "Test Result: 21 tests failing out of a total of 5,670 tests." 5,670 215670 预期输出: "Test Result: 21 tests failing out of a total of 5,670 tests." 5,670 215670 我使用了下面的命令,但它返回了所有数值,无法获取第二个数值 echo "$getTotal
"Test Result: 21 tests failing out of a total of 5,670 tests."
5,670
215670
预期输出:
"Test Result: 21 tests failing out of a total of 5,670 tests."
5,670
215670
我使用了下面的命令,但它返回了所有数值,无法获取第二个数值
echo "$getTotalCount" | jq '.healthReport[0].description' | sed 's/"//g' | sed 's/[^0-9]*//g'
低于输出:
"Test Result: 21 tests failing out of a total of 5,670 tests."
5,670
215670
是否可以获取基于索引的值[0](结果=21)将获取第一个数值,[1](结果=5670)将获取第二个数值?您可以在原始消息中保留空格
echo "$getTotalCount" | jq '.healthReport[0].description' | sed -e 's/^.* of //' -e 's/ tests.*//' -e 's/[^0-9]//g'
这将剥离任何高达“of”的内容,“tests”之后的内容,并且只保留数字
旁注:
jq有很多内置的字符串函数。您可以使用正则表达式在jq中完成完整提取。您可以使用带有自定义字段分隔符的awk来提取数字:
<<<"$getTotalCount" jq -r '.healthReport[0].description' | awk -F'[^0-9,]+' '{ print $3 }'
要将输出保存到变量,只需使用:
num_tests=$(<<<"$getTotalCount" jq -r '.healthReport[0].description' | awk -F'[^0-9,]+' '{ print $3 }')
num\u tests=$(是的……它的JQI输出是否可以将值存储在变量中?它正在工作。我可以使用您的解决方案分配给变量。谢谢。