skip to Main Content

I have a following array

{
  "data": [
    [
      "2.16.1.0",
      "2.16.1.255",
      "256"
    ],
    [
      "2.16.3.0",
      "2.16.3.255",
      "256"
    ],
    [
      "2.16.6.0",
      "2.16.7.255",
      "512"
    ]
  ]
}

I am trying to get the following output of it:

2.16.1.0-2.16.1.255
2.16.3.0-2.16.3.255
2.16.6.0-2.16.7.255

so far I have succeeded in outputting the first two required values

cat ./data.txt | jq -r '.[][]|nth(0,1)'

2.16.1.0
2.16.1.255
2.16.3.0
2.16.3.255
2.16.6.0
2.16.7.255

but how do I merge/join them? Not sure I’m going in the right direction.

2

Answers


  1. You could select the first 2 items in the array (.[0:2]) and then join() that with a -.

    If you need the 2 items dynamic, you could use .[:-1] to just remove the last index. More about the .[x:y] slice can be found in the Array string slice documentation.


    .data[] | .[0:2] | join("-")
    
    .data[] | .[:-1] | join("-")
    

    Both give:

    2.16.1.0-2.16.1.255
    2.16.3.0-2.16.3.255
    2.16.6.0-2.16.7.255
    

    Online JQ Play Demo
    Login or Signup to reply.
  2. String interpolation can work here too:

    jq -r '.data[] | "(.[0])-(.[1])"'
    

    Or string concatenation:

    jq -r '.data[] | .[0] + "-" + .[1]'
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search