Slice Array
The slice array operator takes an array as input and returns a subarray. Like the jq equivalent, .[10:15] will return an array of length 5, starting from index 10 inclusive, up to index 15 exclusive. Negative numbers count backwards from the end of the array.
You may leave out the first or second number, which will refer to the start or end of the array respectively.
Slicing arrays
Given a sample.yml file of:
- cat
- dog
- frog
- cowthen
yq '.[1:3]' sample.ymlwill output
- dog
- frogSlicing arrays - without the first number
Starts from the start of the array
Given a sample.yml file of:
- cat
- dog
- frog
- cowthen
yq '.[:2]' sample.ymlwill output
- cat
- dogSlicing arrays - without the second number
Finishes at the end of the array
Given a sample.yml file of:
- cat
- dog
- frog
- cowthen
yq '.[2:]' sample.ymlwill output
- frog
- cowSlicing arrays - use negative numbers to count backwards from the end
Given a sample.yml file of:
- cat
- dog
- frog
- cowthen
yq '.[1:-1]' sample.ymlwill output
- dog
- frogInserting into the middle of an array
using an expression to find the index
Given a sample.yml file of:
- cat
- dog
- frog
- cowthen
yq '(.[] | select(. == "dog") | key + 1) as $pos | .[0:($pos)] + ["rabbit"] + .[$pos:]' sample.ymlwill output
- cat
- dog
- rabbit
- frog
- cowLast updated
Was this helpful?