I would like to retrieve a value "tenki-deploy-topic" from the below JSON file content. I used this regex grep -o 'topic[^"]*' output.log, then it gets all the files with the topic, instead, I want to use some other key such as "tenki" or "dense".

{ "Topics": [ { "Name": "arn:aws:sns:us-west-2:123456789012:topic-freezing-deploy" }, { "Name": "arn:aws:sns:us-west-2:123456789012:topic-dense-deploy" }, { "Name": "arn:aws:sns:us-west-2:123456789012:topic-tenki-deploy" } ] }
  • 4
    Is there a reason you're trying to use regular expressions, when jq, a purpose-built JSON parser, will do the job? – DopeGhoti Jul 30 '18 at 20:03
  • Question wrong? Did you mean "topic-tenki-deploy" ? – steve Jul 30 '18 at 21:33

Using the typical CLI tools of Linux/Unix such as awk, sed, & grep are almost always the wrong way to go when trying to parse JSON.

My typical goto tool for JSON CLI work at the terminal is jq. It's in all the repos and can be easily installed.

Your problem of how to select just the elements in the Topics array becomes trivial:

$ jq '.Topics[] | select(.Name | contains("topic-tenki-deploy"))' output.log 
  "Name": "arn:aws:sns:us-west-2:123456789012:topic-tenki-deploy"

The above works by taking the elements from the .Topics[] array and then selecting the .Name whose value contains topic-tenki-deploy.


  • 3
    +1 ... or jq -r --arg str "tenki" '.Topics[] | select(.Name | contains($str)).Name | split(":")[-1]' if you want to parameterize the search, and get the bare value of the last component of the Name string – steeldriver Jul 31 '18 at 1:17

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.