给定YAML文件,example.yaml:
node:
sub_node:
get_this:我想使用Mike的get_this和字符串sub_node获得一个包含D4的变量
yaml="$(cat example.yaml)"
nodename=sub_node
sub_yaml= "$(echo "$yaml" | yq -r '.$nodename' )";
# also tried -> sub_yaml= "$(echo "$yaml" | yq -r '.'"$nodename" )";注意,这是一个人为的例子,实际上,sub_node字符串是事先不知道的,所以我需要替换$nodename字符串。
我似乎不知道如何摆脱yq所需的单引号查询字符串。
我该怎么做?
发布于 2023-03-13 13:45:16
使用迈克·法拉赫yq,您可以将nodename shell变量的值作为路径的一部分,通过使用env()函数从实用程序的环境访问它,如下所示:
$ nodename='sub_node' yq '.node[env(nodename)]' example.yaml
get_this:这将访问由node环境变量的值提供的顶级nodename键的分段。
这避免了将shell变量的值注入到yq表达式中,这意味着您可以访问具有点和其他特殊字符的节。
使用安德烈·基斯柳克yq,可以通过内部变量传递子键来完成类似的事情,如下所示:
$ nodename=sub_node
$ yq -y --arg sect "$nodename" '.node[$sect]' example.yaml
get_this: null..。或者通过阅读环境的价值,
$ nodename=sub_node yq -y '.node[$ENV.nodename]' example.yaml
get_this: null发布于 2023-03-13 13:16:11
正如ikkachu的评论所述,我应该使用双引号。
具有讽刺意味的是,由于我在=之后的空间,我的尝试和错误都没有起作用。
我还必须更正上面示例的查找字符串:
nodename=node.sub_node
sub_yaml="$(echo "$yaml" | yq -r ".$nodename" )";
echo $sub_yaml
get_this:https://unix.stackexchange.com/questions/739589
复制相似问题