-
Example yaml (ex.yaml): items:
- name: foo
place: nyc
- name: bar
place: sea
- name: blah
place: nyc
- name: xyz
place: san
- name: abc
place: san script: #!/usr/bin/bash
# limit and filter variable comes from user input (e.g. commandline)
limit=2
filter='.place != "nyc"'
for index in $(yq ".items | .[] | select($filter) | path | .[-1]" ./ex.yaml | head -n $limit)
do # Do something with the selected entries
name=$(yq ".items.$index | .name" ex.yaml)
place=$(yq ".items.$index | .place" ex.yaml)
echo "Hello $name, You live in $place."
done Is there a better concise way to do the above? In particular, is it possible to replace Output:
|
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
You can do it in a single expression like this:
Note the use of strenv/env rather than getting bash to interpolate the env variables in double quotes around the expression - this can simplify quoting in some cases, for instance here we can use double quotes in the expression fro strings. To get rid of the |
Beta Was this translation helpful? Give feedback.
-
[Unrelated] Got a panic when trying below with same yaml file.
|
Beta Was this translation helpful? Give feedback.
-
:O you found a bug! will fix |
Beta Was this translation helpful? Give feedback.
You can do it in a single expression like this:
Note the use of strenv/env rather than getting bash to interpolate the env variables in double quotes around the expression - this can simplify quoting in some cases, for instance here we can use double quotes in the expression fro strings.
To get rid of the
head -n $limit
- you can use the slice array operator (https://mikefarah.gitbook.io/yq/operators/slice-array) to pick the firstlimit
items from the list. This means you need to wrap the results back into an ar…