首页 > 解决方案 > 如何在搜索中将通配符与环境变量结合起来?

问题描述

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

鉴于:

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 搜索部分字符串?

标签: yq

解决方案


您不需要env()操作员来实现这一点。相反,使用单引号来连接查询中的 shell 变量。

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

输出:

sometexthere

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

我已经添加text with spacelevelB演示中。

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

给定变量A="without space",使用替换${A/out/}删除字符串的第一次出现"out"。操作员现在将select搜索通配符字符串"*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

推荐阅读