Home > database >  Linux bash script to get an array of value from a yml file
Linux bash script to get an array of value from a yml file

Time:06-23

I have an environment.yml like

channels:
  - defaults
dependencies:
  - flask
  - gunicorn = 0.22.0
  - pandas=0.21.1
  - pip
  - pip:
    - six==1.14.0
    - requests ==2.21.0
    - pytz

I want to get all python packages in an array.

    packagesArray=("flask" "gunicorn" "pandas" "pip" "six" "requests" "pytz" )

How can we do that?

CodePudding user response:

One way using yq, a handy front end that converts YAML to JSON and then feeds it to jq:

readarray -t packagesArray < <(yq -r '.dependencies | .. | select(type == "string") | sub("=.*";"")' environment.yaml) 

After this, declare -p packagesArray will show

declare -a packagesArray=([0]="flask" [1]="gunicorn " [2]="pandas" [3]="pip" [4]="six" [5]="requests " [6]="pytz")

CodePudding user response:

you can try something like the below in python3:

#!/usr/bin/env python3

import yaml

def read_yaml(filename):
    try:
        with open(filename, 'r') as file:
            data_yml = yaml.safe_load(file)
            return data_yml

    except BaseException as e:
        msg = 'Yaml File: '   str(e)
        print(msg)


data = read_yaml('environment.yml')

for key, value in data.items():
    print(f"\nkey - {key}\nvalue - {value}\n") 

if you still want to use bash then check out the below link:

read yaml bash

  • Related