how to use jq to filter select items not in list?

前端 未结 2 2308
[愿得一人]
[愿得一人] 2021-02-19 17:26

In jq, I can select an item in a list fairly easily:

$ echo \'[\"a\",\"b\",\"c\",\"d\",\"e\"]\' | jq \'.[] | select(. == (\"a\",\"c\"))\'
2条回答
  •  旧时难觅i
    2021-02-19 17:37

    The simplest and most robust (w.r.t. jq versions) approach would be to use the builtin -:

    $ echo '["a","b","c","d","e"]' | jq -c '. - ["a","c"]'
    ["b","d","e"]
    

    If the blacklist is very long and riddled with duplicates, then it might be appropriate to remove them (e.g. with unique).

    Variations

    The problem can also be solved (in jq 1.4 and up) using index and not, e.g.

    ["a","c"] as $blacklist
    | .[] | select( . as $in | $blacklist | index($in) | not) 
    

    Or, with a variable passed in from the command-line (jq --argjson blacklist ...):

    .[] | select( . as $in | $blacklist | index($in) | not) 
    

    To preserve the list structure, one can use map( select( ...) ).

    With jq 1.5 or later, you could also use any or all, e.g.

    def except(blacklist):
      map( select( . as $in | blacklist | all(. != $in) ) );
    

    Special case: strings

    See e.g. Select entries based on multiple values in jq

提交回复
热议问题