如何在jq查询中编写此代码以获得交集?

时间:2018-12-17 07:46:09

标签: arrays json jq intersection

我是jq的新手,

,并希望得到两个数组的交集(使用不同方法link的类似问题,但)。 我设法得到两个数组的并集和两个数组的加法: 即:

A=['a','b','e','c']
B=['g','a','t','c']

我写了:

echo '{"group_a":["A","B","C","ABC"],"group_b":["B","D"]}' | jq .group_a+.group_b

A + B = ['a','b','e','c','g','g','a','t','c']

echo '{"group_a":["A","B","C","ABC"],"group_b":["B","D"]}' | jq .group_a+.group_b | jq 'unique'

A U B = ['a','b','e','c','g','t']

但是我现在如何应用这个简单的逻辑:

intersection = unique((A+B) - (A U B))

我已经习惯了一个内衬,我希望此代码片段可读性强并且易于将来使用。 那么我该如何以jq样式实现呢?

任何帮助都会有所帮助,谢谢大家!

1 个答案:

答案 0 :(得分:2)

假设数组不包含重复项(如果包含重复项,请使用unique来过滤出重复的结果):

jq -cn '["a","b","e","c"] as $A | ["g","a","t","c"] as $B | $A - ($A - $B)'
echo '{ "group_a" : ["a","b","e","c"], "group_b" : ["g","a","t","c"] }' | jq -c '.group_a - (.group_a - .group_b)'

它们都产生:

["a","c"]