Search code examples
bashawksedgrepsh

How to extract data from a JSON file into a variable


I have the following json format, basically it is a huge file with several of such entries.

 [
      {
        "id": "kslhe6em",
        "version": "R7.8.0.00_BNK",
        "hostname": "abacus-ap-hf-test-001:8080",
        "status": "RUNNING",
           },
      {
        "id": "2bkaiupm",
        "version": "R7.8.0.00_BNK",
        "hostname": "abacus-ap-hotfix-001:8080",
        "status": "RUNNING",
      },
      {
        "id": "rz5savbi",
        "version": "R7.8.0.00_BNK",
        "hostname": "abacus-ap-hf-test-005:8080",
        "status": "RUNNING",
          },
          
    ]

I wanted to fetch all the hostname values that starts with "abacus-ap-hf-test" and without ":8080" into a variable and then wanted to use those values for further commands over a for loop something like below. But, am bit confused how can I extract such informaion.

HOSTAME="abacus-ap-hf-test-001 abacus-ap-hf-test-005"
for HOSTANAME in $HOSTNAME
do 
  sh ./trigger.sh
done

Solution

  • The first line command update to this:

    HOSTAME=$(grep -oP 'hostname": "\K(abacus-ap-hf-test[\w\d-]+)' json.file)
    

    or if you sure that the hostname end with :8080", try this:

    HOSTAME=$(grep -oP '(?<="hostname": ")abacus-ap-hf-test[\w\d-]+(?=:8080")' json.file)
    

    you will find that abacus-ap-hf-test[\w\d-]+ is the regex, and other strings are the head or the end of the regex content which for finding result accuracy.