简体   繁体   中英

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

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?

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")

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM