5

I have a json object with one of field having values for example "countries-sapi-1.0", "inventory-list-api-1.0-snapshot"

Note that the first one has sapi and the other one has api.

Using jq, how can i get countries-sapi or inventory-list-api I mean whatever is there before the version. the version can be as simple as 1.0 or 1.0.1-snapshot etc..

peak
  • 105,803
  • 17
  • 152
  • 177
Naveen K Reddy
  • 429
  • 5
  • 13

3 Answers3

5

I got here searching for how to split by regex instead of substring in jq, but I found out that you have to give two arguments to the split function (where the second argument contains flags for the regex, but it can be just an empty string).

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

From the manual:

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.
nisetama
  • 7,764
  • 1
  • 34
  • 21
3

It looks like you need to study up on regular expressions (regex); see for example https://regexone.com/ or https://github.com/zeeshanu/learn-regex or dozens of others.

Using jq, in your particular case, you could start with:

sub(" *- *[0-9]+\\.[0-9]+.*$"; "")

Note that two backslashes are required here because the "from" expression must be (or evaluate to) a valid JSON string.

peak
  • 105,803
  • 17
  • 152
  • 177
1

For input "countries-sapi-1.0", use: .[] | match( "\\d"; "ig") which will give you the following output:

{
  "offset": 15,
  "length": 1,
  "string": "1",
  "captures": []
}
{
  "offset": 17,
  "length": 1,
  "string": "0",
  "captures": []
}

This uses the first object's offset value and tries to slice it from the starting position to the received offset.

Slice from beginning: $ jq -c '.[:15]'

In our case we got 15 as the offset for the first object so we used :15 for the slice.

ggorlen
  • 44,755
  • 7
  • 76
  • 106