shellgrep

How to retrieve single value with grep from Json?


How to extract a single value from a given json?

{
  "Vpc": {
    "InstanceTenancy": "default", 
    "State": "pending", 
    "VpcId": "vpc-123", 
    "CidrBlock": "10.0.0.0/16", 
    "DhcpOptionsId": "dopt-123"
  }
}

Tried this but with no luck:

grep -e '(?<="VpcId": ")[^"]*'

Solution

  • You probably wanted -Po, which works with your regex:

    $ grep -oP '(?<="VpcId": ")[^"]*' infile
    vpc-123
    

    If GNU grep with its -P option isn't available, we can't use look-arounds and have to resort to for example using grep twice:

    $ grep -o '"VpcId": "[^"]*' infile | grep -o '[^"]*$'
    vpc-123
    

    The first one extracts up to and excluding the closing quotes, the second one searches from the end of the line for non-quotes.

    But, as mentioned, you'd be better off properly parsing your JSON. Apart from jq mentioned in another answer, I know of

    A jq solution would be as simple as this:

    $ jq '.Vpc.VpcId' infile 
    "vpc-123"
    

    Or, to get raw output instead of JSON:

    $ jq -r '.Vpc.VpcId' infile 
    vpc-123