Compare three arrays in bash, diff and identical values [duplicate]

风格不统一 提交于 2019-12-02 22:29:34

问题


This question refers to the answered question: Compare/Difference of two arrays in bash

Let's take two arrays:

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

Symetrical Differences between arrays:

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

Array3 values:

echo $Array3
key10
key11
key12
key7
key8
key9

Values only in Array1:

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

Values only in Array2

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

My question, how can we get values that are in Array1 & Array2 but not in Array3 (identical)? Expected result:

key1
key13
key2
key3
key4
key5
key6

Thanks for your help.


回答1:


OK after few test, it seems the answer I was looking for was just:

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



回答2:


You can achieve this by using :

#!/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[@]}"

Output :

key1
key2
key3
key4
key5
key6
key13


来源:https://stackoverflow.com/questions/37651570/compare-three-arrays-in-bash-diff-and-identical-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!