Bash check element in array for elements in another array
CORRECTED#3
Try code bellow. ArrContains
take two arguments, the name of the two arrays. It creates a temporary hash from lArr1
and then check if any elements of lArr2
is in the hash. This way the embedded for
-loops can be avoided.
#!/usr/bin/bash
ArrContains(){
local lArr1 lArr2
declare -A tmp
eval lArr1=("\"\${$1[@]}\"")
eval lArr2=("\"\${$2[@]}\"")
for i in "${lArr1[@]}";{ ((++tmp['$i']));}
for i in "${lArr2[@]}";{ [ -n "${tmp[$i]}" ] && return 0;}
return 1
}
arr1=("a b" b c)
arr2=(x 'b c' e)
arr3=(q a\ b y)
ArrContains arr1 arr2 && echo Contains arr1 arr2
ArrContains arr1 arr3 && echo Contains arr1 arr3
Output:
Contains arr1 arr3
Other way could be to define some separation character and concatenate the first hash. Then search for matching the SEPitemSEP
string.
ArrContainsRe(){
local lArr1 lArr2 tmp
eval lArr1=("\"\${$1[@]}\"")
printf -v tmp ",%s" "${lArr1[@]}";
tmp="$tmp,"
eval lArr2=("\"\${$2[@]}\"")
for i in "${lArr2[@]}";{ [[ $tmp =~ ,$i, ]] && return 0;}
return 1
}
...
ArrContainsRe arr1 arr2 && echo ContainsRe arr1 arr2
ArrContainsRe arr1 arr3 && echo ContainsRe arr1 arr3
Output:
ContainsRe arr1 arr3