如何在不使用jq的Shell脚本中提取文本文件指定值
问题
我有一个名为myfile.txt的文件,内容为JSON格式的项目状态数据:
{"projectStatus":{"status":"ERROR","conditions":[{"status":"ERROR","metricKey":"new_bugs","comparator":"GT","periodIndex":1,"errorThreshold":"0","actualValue":"2"}, {"status":"ERROR","metricKey":"new_reliability_rating","comparator":"GT","periodIndex":1,"errorThreshold":"1","actualValue":"3"}, {"status":"ERROR","metricKey":"new_security_rating","comparator":"GT","periodIndex":1,"errorThreshold":"1","actualValue":"2"}, {"status":"OK","metricKey":"new_maintainability_rating","comparator":"GT","periodIndex":1,"errorThreshold":"1","actualValue":"1"}, {"status":"ERROR","metricKey":"new_code_smells","comparator":"GT","periodIndex":1,"errorThreshold":"0","actualValue":"17"}, {"status":"ERROR","metricKey":"new_vulnerabilities","comparator":"GT","periodIndex":1,"errorThreshold":"0","actualValue":"2"}, {"status":"ERROR","metricKey":"coverage","comparator":"LT","errorThreshold":"90","actualValue":"80.3"}, {"status":"ERROR","metricKey":"new_coverage","comparator":"LT","periodIndex":1,"errorThreshold":"90","actualValue":"7.826086956521739"}], "periods":[{"index":1,"mode":"previous_version","date":"2021-11-04T14:47:41+0000"}],"ignoredConditions":false}}
需要提取其中metricKey为"new_coverage"对应的actualValue值(即7.826086956521739),预期输出:
7.826086956521739
我尝试过以下sed命令但未成功:
sed -n 's/"metricKey":"new_coverage" "actualValue": //p' myfile.txt
注意:不允许使用jq或Python、JavaScript等通用脚本语言。
解决方案
方法1:修正后的sed命令
原命令失效的原因是:"metricKey":"new_coverage"与"actualValue"之间不是空格,而是包含逗号和空格;同时没有匹配actualValue值的引号结构。使用以下命令可实现需求:
sed -n 's/.*"metricKey":"new_coverage".*"actualValue":"\([^"]*\)".*/\1/p' myfile.txt
核心逻辑:
.*:匹配任意长度的前置内容,快速定位到目标metricKey"actualValue":"\([^"]*\)":用分组捕获actualValue引号内的所有内容([^"]*表示匹配除引号外的任意字符)\1:仅输出捕获到的目标值
方法2:使用awk命令
如果觉得sed正则过于复杂,也可以用awk处理:
awk -F'"' '/"metricKey":"new_coverage"/{for(i=1;i<=NF;i++){if($i=="actualValue"){print $(i+2)}}}' myfile.txt
核心逻辑:
-F'"':以双引号作为字段分隔符- 匹配包含目标
metricKey的行后,遍历所有字段,找到值为actualValue的字段,输出其后第2个字段(即目标值)
内容的提问来源于stack exchange,提问作者Zero5
相关产品推荐
相关产品推荐

