How to grep specific value based on matching search value

You can try this with GNU awk:

awk -F',' 'BEGIN { RS = "--" } /"lifecycle-state": "AVAILABLE"/ {  gsub("^[[:blank:]]*", "", $1);  print $1 }' file

Output:

"db-unique-name":"p00z5bj_iad2bj"

If you're dealing with JSON formatted data (the fragments look like it) you should certainly have a look at jq which is a pretty useful tool for such data.

If your data looks like this

{
    "db-unique-name": "p00z5bj_iad2bj",
      "db-workload": "OLTP",
      "defined-tags": {},
      "freeform-tags": {},
      "id": "dfadfasfsadfasdfasdf",
      "lifecycle-details": null,
      "lifecycle-state": "AVAILABLE"
}
{
      "db-unique-name": "p00u5bh_iad2bj",
      "db-workload": "OLTP",
      "defined-tags": {},
      "freeform-tags": {},
      "id": "asdfsadfasdfasfd",
      "lifecycle-details": "Resource was terminated at the backend.",
      "lifecycle-state": "FAILED"
}
{
      "db-unique-name": "p00u5bh_iad2bj",
      "db-workload": "OLTP",
      "defined-tags": {},
      "freeform-tags": {},
      "id": "asdfasdfasdf",
      "lifecycle-details": "Resource was terminated at the backend.",
      "lifecycle-state": "FAILED"
}

then this jq statement

jq 'select(."lifecycle-state" == "AVAILABLE") | ."db-unique-name" ' < db_systems.txt

will output

"p00z5bj_iad2bj"

However, if your file actually looks like the example you've given (with -- as separators and no {} object notation) then the awk solution might be easier, it's somewhat difficult to shove non-JSON data into jq...


Try this,

Using grep:

 grep -B6 AVAILABLE file | grep db-unique-name
 "db-unique-name": "p00z5bj_iad2bj",
  • B Print NUM lines of leading context before matching lines.

Using awk:

 awk '{a[++i]=$0;}/AVAILABLE/{print a[NR-6];}' file
 "db-unique-name": "p00z5bj_iad2bj",