如何结合通配符(s)与环境变量在搜索?



是否可以在查询中使用带有通配符的环境变量?

给定:

LevelA:
levelB:
- sometexthere
- other.value.here

下面的查询:

yq eval '.LevelA.levelB.[] | select(. == "*text*")' $file

返回:sometexthere.

也可以使用环境变量:

A="sometexthere" yq eval '.LevelA.levelB.[] | select(. == env(A) )' $file

返回相同的值:sometexthere。但是,这有点无意义,因为输出与输入变量值相同。

如果通配符与环境变量组合(以匹配部分字符串),则命令不返回任何内容:

A=text yq eval '.LevelA.levelB.[] | select(. == "*env(A)*")' $file

是否有另一种方法可以用yq搜索使用环境变量的部分字符串?

您不需要env()操作符来实现此操作。相反,在查询中使用单引号来连接shell变量。

A="text"
yq eval '.LevelA.levelB.[] | select(. == "*'$A'*" )' file.yml

输出:

sometexthere

使用这种技术,您可以利用bash参数展开。

我将text with space添加到levelB中来演示。

# file.yml
LevelA:
levelB:
- sometexthere
- other.value.here
- text with space

给定变量A="without space",使用替换${A/out/}来删除字符串"out"的第一个出现。select操作符现在将搜索通配符string"*with space*".

A="without space"    
yq eval '.LevelA.levelB.[] | select(. == "*'"${A/out/}"'*" )' file.yml
#       |                                | ||     |   || |  |
#       |                                | ||     |   || |  └> (a.1) end yq query
#       |                                | ||     |   || └> (b) end string
#       |                                | ||     |   |└> (a.2) open yq query (end concat)
#       |                                | ||     |   └> (c) bash double quote
#       |                                | ||     └> remove the first occurent of "out"
#       |                                | |└> (c) bash double quote
#       |                                | └> (a.2) close yq query (begin concat)
#       |                                └> (b) begin string
#       └> (a.1) start yq query

输出:

text with space

最新更新