I have a few files that contains a similar entry like as follows:

{"result":[{"alternative":[{"transcript":"I win","confidence":0.87958056},{"transcript":"when"},{"transcript":"Schwinn"},{"transcript":"Gwen"},{"transcript":"I went"}],"final":true}],"result_index":0}

Basically there's a string that has a "confidence" associated with it. This string always appears before the string "confidence". In this case, the target string is "I win". Using command line linux tools, how would I parse this file to get the target string?


The "simple" answer is to use sed:

sed -n 's/.*\("[^"]*"\),"confidence".*/\1/p' filename

This will print "I win".  To exclude the quotes (and get just I win as the output), move the first two double quotes in the command outside of the parentheses:

sed -n 's/.*"\([^"]*\)","confidence".*/\1/p' filename

The better answer is to get a tool that's designed to parse JSON data.


It's JSON, and linux tools are not very good for working with JSON. And your conditions are not very clear... But this perl one-liner produces from your example string "I win"

perl -0777 -nE 's/.*"(.+?)","confidence".*/$1/s; say'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.