jq 按模式分割字符串

Nav*_*ddy 7 regex json split substring jq

我有一个 json 对象,其中一个字段的值例如“ countries- sapi-1.0 ”、“ inventory-list- api-1.0-snapshot

请注意,第一个有sapi,另一个有api

使用jq,我怎样才能获得country-sapi或inventory-list-api我的意思是版本之前的任何内容。版本可以很简单,例如1.01.0.1-snapshot等等。

nis*_*ama 7

我在这里搜索如何通过正则表达式而不是 in 中的子字符串进行分割jq,但我发现您必须为该split函数提供两个参数(其中第二个参数包含正则表达式的标志,但它可以只是一个空字符串)。

$ jq -n '"axxbxxxc"|split("x+";"")'
[
  "a",
  "b",
  "c"
]
Run Code Online (Sandbox Code Playgroud)

从手册中:

split
    Splits an input string on the separator argument.

        jq 'split(", ")'
           "a, b,c,d, e, "
        => ["a","b,c,d","e",""]

[...]

split(regex; flags)
    For backwards compatibility, split splits on a string, not a regex.
Run Code Online (Sandbox Code Playgroud)


pea*_*eak 3

看来你需要好好研究一下正则表达式(regex);例如,请参阅https://regexone.com/https://github.com/zeeshanu/learn-regex或其他几十个。

使用 jq,在您的特定情况下,您可以从以下开始:

sub(" *- *[0-9]+\\.[0-9]+.*$"; "")
Run Code Online (Sandbox Code Playgroud)

请注意,此处需要两个反斜杠,因为“from”表达式必须是(或计算结果为)有效的 JSON 字符串。