The slice operator works on both arrays and strings. Like the jq equivalent, .[10:15] will return a subarray (or substring) of length 5, starting from index 10 inclusive, up to index 15 exclusive. Negative numbers count backwards from the end of the array or string.
You may leave out the first or second number, which will refer to the start or end of the array or string respectively.
Given a sample.yml file of:
- cat
- dog
- frog
- cowthen
yq '.[1:3]' sample.ymlwill output
- dog
- frogStarts from the start of the array
Given a sample.yml file of:
- cat
- dog
- frog
- cowthen
yq '.[:2]' sample.ymlwill output
- cat
- dogFinishes at the end of the array
Given a sample.yml file of:
- cat
- dog
- frog
- cowthen
yq '.[2:]' sample.ymlwill output
- frog
- cowGiven a sample.yml file of:
- cat
- dog
- frog
- cowthen
yq '.[1:-1]' sample.ymlwill output
- dog
- frogusing 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
- cowGiven a sample.yml file of:
country: Australiathen
yq '.country[4:]' sample.ymlwill output
raliaFinishes at the end of the string
Given a sample.yml file of:
country: Australiathen
yq '.country[0:5]' sample.ymlwill output
AustrStarts from the start of the string
Given a sample.yml file of:
country: Australiathen
yq '.country[:5]' sample.ymlwill output
AustrNegative indices count from the end of the string
Given a sample.yml file of:
country: Australiathen
yq '.country[-5:]' sample.ymlwill output
ralia