比较 bash、diff 和相同值中的三个数组



这个问题指的是回答的问题: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 `)

数组 3 值:

echo $Array3
key10
key11
key12
key7
key8
key9

仅在数组 1 中的值:

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

仅在数组 2 中的值

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

我的问题是,我们如何获得 Array1 和 Array2 中的值,而不是 Array3(相同)中的值?预期成果:

key1
key13
key2
key3
key4
key5
key6

感谢您的帮助。

经过几次测试后好的,似乎我正在寻找的答案只是:

echo ${Array1[@]} ${Array2[@]} | tr ' ' 'n' | sort | uniq -D | uniq
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 '%sn' "${intersections[@]}"

输出:

key1
key2
key3
key4
key5
key6
key13

相关内容

  • 没有找到相关文章