Skip to content

Filter an array and iterate on selected entries in shell script #1511

Answered by mikefarah
balki asked this question in Q&A

You must be logged in to vote

You can do it in a single expression like this:

filter='.place != "nyc"' limit=2 yq '
   [.items | .[] | select(strenv(filter))] | 
   .[:env(limit)] | .[]  | 
   ("hello " + .name + ", You live in " + .place + ".")' file.yaml

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 first limit items from the list. This means you need to wrap the results back into an ar…

Replies: 3 comments 2 replies

You must be logged in to vote
2 replies
@balki

@mikefarah

Answer selected by balki

You must be logged in to vote
0 replies

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants