how to fetch a selected value from a text file using a shell script

Viewed 62

I have a file which looks like this (myfile.txt)

{"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}}

I have to pick "actualValue":"7.826086956521739" which is with "metricKey":"new_coverage"

then expected output is (actualValue)

7.826086956521739

this is what I tried

sed -n 's/"metricKey":"new_coverage" "actualValue": //p' myfile.txt 

Can someone help me to figure out this? Thanks in advance!

Note: I am not allowed to use jq or a general purpose scripting language (JavaScript, Python etc).

3 Answers
$ sed -n 's/.*"metricKey":"new_coverage".*"actualValue":"\([^"]*\)".*/\1/p' file
7.826086956521739

For Future readers in case anyone needs an answer in jq(Adding this answer here, though OP says OP can't use it). With jq which is json aware tool, you could try following answer. Written and tested with shown samples. Using jq's -r option to get data in raw output form and then selecting appropriate component value where checking if value of metricKey is new_coverage then print it's actualValue component value.

jq -r '.[] | .conditions[] | select(.metricKey=="new_coverage").actualValue' Input_file

OR a non-one liner form of above solution:

jq -r '.[]    | 
.conditions[] | 
select(.metricKey=="new_coverage").actualValue
'  Input_file

Output will be as follows: 7.826086956521739

{m,g,n}awk 'NF*=NF==3' FS='^.+"metricKey":"new_coverage".+actualValue":"|[^0-9]+$' OFS=

7.826086956521739

|

{m,g,n}awk '$!NF = sprintf("%.*s",NF*=NF==3,$-_)' OFS= \
              FS='^.+"metricKey":"new_coverage".+actualValue":"|[^0-9]+$' 

7.8
Related