[英]Find common and unique items between two arrays
我使用帶有ansible的ec2.py動態清單腳本來提取ec2主機及其標記名稱的列表。 它向我返回如下的JSON列表,
"tag_aws_autoscaling_groupName_asg_test": [
"aa.b.bb.55",
"1b.b.c.d"
],
"tag_aws_autoscaling_groupName_asg_unknown": [
"aa.b.bb.55",
"1b.b.c.e"
],
我正在使用jq解析此輸出。
由於在數組上定義jq的“-”運算符的方式, unique
一次調用足以產生“唯一化”的答案:
def difference($a; $b): ($a | unique) - $b;
類似地,對於對稱差異,單個排序操作足以產生“唯一”值:
def sdiff($a; $b): (($a-$b) + ($b-$a)) | unique;
這是應與jq的所有版本一起使用的更快的intersect/2
版本-消除了group_by
,從而支持sort
:
def intersect(x;y):
( (x|unique) + (y|unique) | sort) as $sorted
| reduce range(1; $sorted|length) as $i
([];
if $sorted[$i] == $sorted[$i-1] then . + [$sorted[$i]] else . end) ;
如果您有jq 1.5,則這是一個類似但仍可測量得更快的set-intersection函數:它在兩個數組的set-intersection中生成元素流:
def intersection(x;y):
(x|unique) as $x | (y|unique) as $y
| ($x|length) as $m
| ($y|length) as $n
| if $m == 0 or $n == 0 then empty
else { i:-1, j:-1, ans:false }
| while( .i < $m and .j < $n;
$x[.i+1] as $nextx
| if $nextx == $y[.j+1] then {i:(.i+1), j:(.j+1), ans: true, value: $nextx}
elif $nextx < $y[.j+1] then .i += 1 | .ans = false
else .j += 1 | .ans = false
end )
end
| if .ans then .value else empty end ;
要查找兩個數組之間的公共項,只需在兩個數組之間執行設置的交集即可。 沒有可用的交集函數,但它應該足夠簡單以自行定義。 取每個數組的唯一項,按值將它們分組,然后取一組中大於1的項。
def intersect($a; $b): [($a | unique)[], ($b | unique)[]]
| [group_by(.)[] | select(length > 1)[0]];
使用它來查找公共元素(假設您的輸入實際上是有效的json對象):
$ jq 'def intersect($a; $b): [($a | unique)[], ($b | unique)[]]
| [group_by(.)[] | select(length > 1)[0]];
intersect(.tag_aws_autoscaling_groupName_asg_test;
.tag_aws_autoscaling_groupName_asg_unknown)' < input.json
[
"aa.b.bb.55"
]
要查找數組唯一的項目,只需執行設置差。
$ jq 'def difference($a; $b): ($a | unique) - ($b | unique);
difference(.tag_aws_autoscaling_groupName_asg_test;
.tag_aws_autoscaling_groupName_asg_unknown)' < input.json
[
"1b.b.c.d"
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.