@ilya-bystrov's most upvoted answer calculates the difference of Array1
and Array2
. Please note that this is not the same as removing items from Array1
that are also in Array2
. @ilya-bystrov's solution rather concatenates both lists and removes non-unique values. This is a huge difference when Array2
includes items that are not in Array1
: Array3
will contain values that are in Array2
, but not in Array1
.
Here's a pure Bash solution for removing items from Array1
that are also in Array2
(note the additional "key11"
in Array2
):
Array1=( "key1" "key2" "key3" "key4" "key5" "key6" "key7" "key8" "key9" "key10" )
Array2=( "key1" "key2" "key3" "key4" "key5" "key6" "key11" )
Array3=( $(printf "%s\n" "${Array1[@]}" "${Array2[@]}" "${Array2[@]}" | sort | uniq -u) )
Array3
will consist of "key7" "key8" "key9" "key10"
and exclude the unexpected "key11"
when trying to remove items from Array1
.
If your array items might contain whitespaces, use mapfile
to construct Array3
instead, as suggested by @David:
Array1=( "key1" "key2" "key3" "key4" "key5" "key6" "key7" "key8" "key9" "key10" "key10" )
Array2=( "key1" "key2" "key3" "key4" "key5" "key6" "key11" )
mapfile -t Array3 < <(printf "%s\n" "${Array1[@]}" "${Array2[@]}" "${Array2[@]}" | sort | uniq -u)
Please note: This assumes that all values in Array1
are unique. Otherwise they won't show up in Array3
. If Array1
contains duplicate values, you must remove the duplicates first (note the duplicate "key10"
in Array1
; possibly use mapfile
if your items contain whitespaces):
Array1=( "key1" "key2" "key3" "key4" "key5" "key6" "key7" "key8" "key9" "key10" "key10" )
Array2=( "key1" "key2" "key3" "key4" "key5" "key6" "key11" )
Array3=( $({ printf "%s\n" "${Array1[@]} | sort -u; printf "%s\n" "${Array2[@]}" "${Array2[@]}"; } | sort | uniq -u) )
If you want to replicate the duplicates in Array1
to Array2
, go with @ephemient' accepted answer. The same is true if Array1
and Array2
are huge: this is a very inefficient solution for a lot of items, even though it's negligible for a few items (<100). If you need to process huge arrays don't use Bash.