'Parse YAML using shell

I have a yaml something of this sort and need to parse and get the value of 'url' here.

name: Yaml_Test
servers:
- name: host_ip
  host: host_name
  port: 443
  scheme: https

variables:
- constant:
    name: url
    value: https://url_here


Solution 1:[1]

With the current versions of both kislyuk/yq and mikefarah/yq, use select to filter the array items:

.variables[].constant | select(.name == "url").value
https://url_here

Using kislyuk/yq, you may want to add the -r option to output raw text:

yq -r '…' file.yaml

Using an older version of mikefarah/yq, you need to specify the command e or eval:

yq e '…' file.yaml

Edit: Although not recommended, here's as requested in a comment a grep-only solution which heavily relies on how the YAML document is represented textually, based on the sample provided (i.e. no other occurrence of name: url etc.):

grep -A1 'name: url' file.yaml | grep -o 'http.*'
https://url_here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1