bash中两个数组的比较/差异

是否有可能采取bash中两个数组的差异。

如果您可以建议我这样做的话,那真的很棒。


代码:


Array1=( "key1" "key2" "key3" "key4" "key5" "key6" "key7" "key8" "key9" "key10" )

Array2=( "key1" "key2" "key3" "key4" "key5" "key6" ) 


Array3 =diff(Array1, Array2)


Array3 ideally should be :

Array3=( "key7" "key8" "key9" "key10" )

感谢您的帮助。


一只斗牛犬
浏览 1086回答 3
3回答

蛊毒传说

echo ${Array1[@]} ${Array2[@]} | tr ' ' '\n' | sort | uniq -u输出量key10key7key8key9您可以根据需要添加排序

白板的微信

每当出现一个问题,处理可能无法排序的唯一值时,我的脑子立刻就醒悟。这是我的看法。码#!/bin/bashdiff(){&nbsp; awk 'BEGIN{RS=ORS=" "}&nbsp; &nbsp; &nbsp; &nbsp;{NR==FNR?a[$0]++:a[$0]--}&nbsp; &nbsp; &nbsp; &nbsp;END{for(k in a)if(a[k])print k}' <(echo -n "${!1}") <(echo -n "${!2}")}Array1=( "key1" "key2" "key3" "key4" "key5" "key6" "key7" "key8" "key9" "key10" )Array2=( "key1" "key2" "key3" "key4" "key5" "key6" )Array3=($(diff Array1[@] Array2[@]))echo ${Array3[@]}输出量$ ./diffArray.shkey10 key7 key8 key9*注意**:像给出的其他答案一样,如果数组中有重复的键,则它们只会被报告一次;这可能是或不是您正在寻找的行为。用于处理该问题的awk代码更加混乱,而且不够干净。
打开App,查看更多内容
随时随地看视频慕课网APP