Naveen K Reddy
Naveen K Reddy

Reputation: 499

jq split string by a pattern

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..

Upvotes: 8

Views: 14608

Answers (4)

ggorlen
ggorlen

Reputation: 56965

Another option, using match and assuming versions start with /-\d+\./:

$ echo '["countries-sapi-1.0", "inventory-list-api-1.0-snapshot"]' | \
jq '.[] | match("^.*(?=-\\d+\\.)") | .string'
"countries-sapi"
"inventory-list-api"

If you can assume all versions start with -1.:

$ echo '["countries-sapi-1.0", "inventory-list-api-1.0-snapshot"]' | \
jq '.[] | split("-1.") | first'
"countries-sapi"
"inventory-list-api"

Upvotes: 0

Rahul Naiknaware
Rahul Naiknaware

Reputation: 125

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.

Upvotes: 1

nisetama
nisetama

Reputation: 8863

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.

Upvotes: 8

peak
peak

Reputation: 116750

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.

Upvotes: 3

Related Questions