pkg/yqlib/doc/operators/slice-array.md
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
- cow
then
yq '.[1:3]' sample.yml
will output
- dog
- frog
Starts from the start of the array
Given a sample.yml file of:
- cat
- dog
- frog
- cow
then
yq '.[:2]' sample.yml
will output
- cat
- dog
Finishes at the end of the array
Given a sample.yml file of:
- cat
- dog
- frog
- cow
then
yq '.[2:]' sample.yml
will output
- frog
- cow
Given a sample.yml file of:
- cat
- dog
- frog
- cow
then
yq '.[1:-1]' sample.yml
will output
- dog
- frog
using an expression to find the index
Given a sample.yml file of:
- cat
- dog
- frog
- cow
then
yq '(.[] | select(. == "dog") | key + 1) as $pos | .[0:($pos)] + ["rabbit"] + .[$pos:]' sample.yml
will output
- cat
- dog
- rabbit
- frog
- cow
Given a sample.yml file of:
country: Australia
then
yq '.country[0:5]' sample.yml
will output
Austr
Finishes at the end of the string
Given a sample.yml file of:
country: Australia
then
yq '.country[5:]' sample.yml
will output
alia
Starts from the start of the string
Given a sample.yml file of:
country: Australia
then
yq '.country[:5]' sample.yml
will output
Austr
Negative indices count from the end of the string
Given a sample.yml file of:
country: Australia
then
yq '.country[-5:]' sample.yml
will output
ralia
Indices are rune-based, so multi-byte characters are handled correctly
Given a sample.yml file of:
greeting: héllo
then
yq '.greeting[1:3]' sample.yml
will output
él