这个问题涉及回答的问题: 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
感谢您的帮助。
答案 0 :(得分:1)
好几次测试后,似乎我正在寻找的答案只是:
echo ${Array1[@]} ${Array2[@]} | tr ' ' '\n' | sort | uniq -D | uniq
key1
key13
key2
key3
key4
key5
key6
答案 1 :(得分:0)
您可以使用以下方法实现此目的:
send() / receive()
输出:
#!/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[@]}"