Reputation: 5031
i have two array of numbers, first array have all numbers while the second has a subset of first one, how can i write a script to find the missing number which exist in the first array but not in the second array?
Array 1: [0, 1, 2, ..79] Array 2: [1, 12, 33, 54,60, 71]
i googled around and tried different approaches i found but none of them worked
1.
declare -a array3
for i in "${array1[@]}"
if [[ "${array2[@]}" =~ "$i" || "${array2[${#array2[@]}-1]}" == "$i" ]]; then
else
array3+=("$i")
fi
done
2.
array3=()
for i in "${array1[@]}";do
skip=
for j in "$array2[@]";do
[[ $i == $j ]] && { skip=1; break; }
done
[[ -n $skip ]] || array3+=("$i")
done
declare -p array3
i m new to bash script, please help!
Upvotes: 2
Views: 510
Reputation: 785058
One way to get array differential is using comm
:
array1=(0 1 2 3 4 5 6 7 8 9 10 11 12)
array2=(0 1 3 4 6 7 10 12)
comm -23 <(printf "%s\n" "${array1[@]}" | sort) <(printf "%s\n" "${array2[@]}" | sort) | sort -n
2
5
8
9
11
Upvotes: 4