问题
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