jq 测试字符串中是否有多个子字符串

jq test if any of several substrings is in a string

假设我有一个这样的项目列表:

[
  "abcdef",
  "defghi",
  "euskdh"
]

我想编写一个过滤器,returns 所有包含 "a"、"d" 或 "h" 的项目。这是我能想到的最好的:

. as $val | select(any(["a", "d", "h"]; inside($val)))

有没有不用变量的方法?

假设您的 jq 支持正则表达式:

map(select(test("a|d|h")))

或者,如果您想要一个值流:

.[] | select(test("a|d|h"))

如果您的 jq 不支持正则表达式,那么如果它支持 any/2,以下将生成一个值流:

.[] | select( any( index( "a", "d", "h"); . != null ) )

所有其他方法都失败了,以下将完成工作但效率低下:

 .[] | select( [index("a", "d", "h")] | any )

这是一个使用 index

的解决方案
  .[]
| if index("a") or index("d") or index("h") then . else empty end