0

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.

jww
  • 97,681
  • 90
  • 411
  • 885
Benjamin Bohec
  • 118
  • 2
  • 11
  • 1
    That code for symmetrical difference breaks if the arrays contain data they were designed to contain: elements that contain whitespace. – chepner Jun 06 '16 at 12:36

2 Answers2

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
Benjamin Bohec
  • 118
  • 2
  • 11
0

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
Rahul
  • 402
  • 2
  • 9
  • 23
  • Hi @arzyfex. Thanks for your answer but it don't work if my diff Array3 is empty. I can add a condition if Array3 is empty. Can we do the same thing with the echo style provided in Array3 ? – Benjamin Bohec Jun 06 '16 at 13:07