如何解决如何在搜索中将通配符与环境变量相结合?
给定:
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 parameter-expansions。
我已将 text with space
添加到 levelB
以进行演示。
# 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。