如何从 Linux shell 脚本解析 YAML 文件? [英] How can I parse a YAML file from a Linux shell script?

查看:547
本文介绍了如何从 Linux shell 脚本解析 YAML 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望提供一个结构化的配置文件,它让非技术用户尽可能容易地进行编辑(不幸的是它必须是一个文件),所以我想使用 YAML.但是,我找不到任何从 Unix shell 脚本解析它的方法.

I wish to provide a structured configuration file which is as easy as possible for a non-technical user to edit (unfortunately it has to be a file) and so I wanted to use YAML. I can't find any way of parsing this from a Unix shell script however.

推荐答案

我的用例可能与原帖所要求的完全相同,也可能不同,但绝对相似.

My use case may or may not be quite the same as what this original post was asking, but it's definitely similar.

我需要引入一些 YAML 作为 bash 变量.YAML 的深度永远不会超过一层.

I need to pull in some YAML as bash variables. The YAML will never be more than one level deep.

YAML 看起来像这样:

YAML looks like so:

KEY:                value
ANOTHER_KEY:        another_value
OH_MY_SO_MANY_KEYS: yet_another_value
LAST_KEY:           last_value

像-a dis一样输出:

Output like-a dis:

KEY="value"
ANOTHER_KEY="another_value"
OH_MY_SO_MANY_KEYS="yet_another_value"
LAST_KEY="last_value"

我用这一行实现了输出:

I achieved the output with this line:

sed -e 's/:[^:\/\/]/="/g;s/$/"/g;s/ *=/=/g' file.yaml > file.sh

  • s/:[^:\/\/]/="/g 找到 : 并将其替换为 =",而忽略 ://(对于 URL)
  • s/$/"/g" 附加到每一行的末尾
  • s/*=/=/g 删除 =
  • 之前的所有空格

    • s/:[^:\/\/]/="/g finds : and replaces it with =", while ignoring :// (for URLs)
    • s/$/"/g appends " to the end of each line
    • s/ *=/=/g removes all spaces before =
    • 这篇关于如何从 Linux shell 脚本解析 YAML 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆