使用shell遍历yaml

时间:2018-07-22 19:41:08

标签: bash shell loops yaml

我有一个config_file.yml文件为:

sample:
    sql: "select * from dbname.tableName where sampleDate>='2018-07-20';"
    config: {'hosts': [!!python/tuple ['192.162.0.10', 3001]]}

sample2:
    sql: "select * from dbname.tableName where sampleDate<='2016-05-25';"
    config: {'hosts': [!!python/tuple ['190.160.0.10', 3002]]}

我想使用shell脚本遍历其键值对直到EOF。基本上,我希望能够遍历每个sql直到EOF,并在shell循环中执行每个sql。

试图浏览大量文档,但是他们没有足够的信息了解如何使用shell遍历yaml。

任何想法或示例都将非常有帮助...

谢谢!

编辑:

我已经在使用->

parse_yaml() {
local prefix=$2
local s='[[:space:]]*' w='[a-zA-Z0-9_]*' fs=$(echo @|tr @ '\034')
sed -ne "s|^\($s\)\($w\)$s:$s\"\(.*\)\"$s\$|\1$fs\2$fs\3|p" -e "s|^\($s\)\($w\)$s:$s\(.*\)$s\$|\1$fs\2$fs\3|p" $1 |
awk -F$fs '{
  indent = length($1)/2;
  vname[indent] = $2;
  for (i in vname) {
     if (i > indent) {delete vname[i]}}
  if (length($3) > 0) {
     vn=""; for (i=0; i<indent; i++) {vn=(vn)(vname[i])("_")}
     printf("%s%s%s=\"%s\"\n", "'$prefix'",vn, $2, $3);
  }
}'
}
# read yaml file
eval $(parse_yaml config_file.yml "")
# access yaml content
echo $sample_sql

我无法理解如何进行迭代。

2 个答案:

答案 0 :(得分:4)

为什么不能使用python?

大多数Linux发行版中都应该预装了它,这意味着您不必重新发明轮子!

要设置:

pip install pyyaml

然后您的脚本是:

import yaml
f = open('config_file.yml')
yaml_file = yaml.safe_load(f)
for sample in yaml_file:
    print yaml_file[sample]["sql"]

要运行:

python <script_name>.py

答案 1 :(得分:0)

您可以将greppcregrep与以下内容一起使用:

$ while read -r line; do
  echo $line
done < <(grep -oP "sql: \"\K.+?(?=\")" config_file.yml)

输出:

select * from dbname.tableName where sampleDate>='2018-07-20';
select * from dbname.tableName where sampleDate<='2016-05-25';

在macOS中,您可以使用pcregrep -o "sql: \"\K.+?(?=\")" config_file.yml

可以将\K理解为排除在它前面左边的所有内容,只返回右边的部分.+?(?=\"),直到找到"

现在,如果您的yaml比较复杂,您也可以尝试yqpip install yq),然后例如获取sql的值:

$ yq -r '.sample.sql' config_file.yml