比较 bash 中的三个数组,差异和相同的值

Compare three arrays in bash, diff and identical values

本题参考回答问题: Compare/Difference of two arrays in bash

让我们取两个数组:

Array1=( "key1" "key2" "key3" "key4" "key5" "key6" "key7" "key8" "key9" "key10" "key13" )
Array2=( "key1" "key2" "key3" "key4" "key5" "key6" "key11" "key12" "key13" )

数组之间的对称差异:

Array3=(`echo ${Array1[@]} ${Array2[@]} | tr ' ' '\n' | sort | uniq -u `)

Array3 值:

echo $Array3
key10
key11
key12
key7
key8
key9

仅在 Array1 中的值:

echo ${Array1[@]} ${Array3[@]} | tr ' ' '\n' | sort | uniq -D | uniq
key10
key7
key8
key9

仅在 Array2 中的值

echo ${Array2[@]} ${Array3[@]} | tr ' ' '\n' | sort | uniq -D | uniq
key11
key12

我的问题是,我们如何获取 Array1 和 Array2 中但不在 Array3 中的值(相同)? 预期结果:

key1
key13
key2
key3
key4
key5
key6

感谢您的帮助。

您可以通过以下方式实现:

#!/bin/bash

Array1=( "key1" "key2" "key3" "key4" "key5" "key6" "key7" "key8" "key9" "key10" "key13" )
Array2=( "key1" "key2" "key3" "key4" "key5" "key6" "key11" "key12" "key13" )

Array3=(`echo ${Array1[@]} ${Array2[@]} | tr ' ' '\n' | sort | uniq -u `)

intersections=()

for item1 in "${Array1[@]}"; do
    for item2 in "${Array2[@]}"; do
        for item3 in "${Array3[@]}"; do
            if [[ $item1 == "$item2" && $item1 != "$item3" ]]; then
                    intersections+=( "$item1" )
                    break
            fi
        done
    done
done

printf '%s\n' "${intersections[@]}"

输出:

key1
key2
key3
key4
key5
key6
key13

好吧,经过几次测试,看来我要找的答案就是:

echo ${Array1[@]} ${Array2[@]} | tr ' ' '\n' | sort | uniq -D | uniq
key1
key13
key2
key3
key4
key5
key6