我有两个数组,我如何获得只出现在第二个数组中而在第一个数组中不可用的元素列表?
数组1=(“A”“B”“C”“D”) 数组2=(“B”“E”“G”)
我需要输出,Array3=("E" "G")因为 Array1 中不存在 E 和 G。我使用了@ephemient @SiegeX 答案,但这并没有返回我需要的东西。
function arraydiff() {
awk 'BEGIN{RS=ORS=" "}
{NR==FNR?a[$0]++:a[$0]--}
END{for(k in a)if(a[k])print k}' <(echo -n "${!1}") <(echo -n "${!2}")
}
Array1=( "A" "B" "C" "D" )
Array2=( "B" "E" "G" )
Array3=($(arraydiff Array1[@] Array2[@]))
Run Code Online (Sandbox Code Playgroud)
使用comm。下列:
comm -13 <(printf "%s\n" "${array1[@]}" | sort) <(printf "%s\n" "${array2[@]}" | sort)
Run Code Online (Sandbox Code Playgroud)
将输出E和G。然后您可以使用 将其读取到数组中readarray。
使用关联数组存储第一个数组的元素,并查看第二个数组的元素是否作为键出现在其中:
#!/usr/bin/env bash
arraydiff() {
# Use namerefs for the arrays to work around not being to pass
# two different arrays as function arguments otherwise
local -n a1=$1 a2=$2
# Populate an associative array with the elements of the first array
local -A elems
local elem
for elem in "${a1[@]}"; do
elems[$elem]=1
done
# If an element of the second array doesn't appear in the associative
# array, print it.
for elem in "${a2[@]}"; do
if [[ ! -v elems[$elem] ]]; then
printf "%s\n" "$elem"
fi
done
}
declare -a array1=( A B C D ) array2=( B E G )
readarray -t array3 < <(arraydiff array1 array2)
printf "%s\n" "${array3[@]}"
Run Code Online (Sandbox Code Playgroud)