# Searching for all the array elements in another array?

This is how I would search for an element in an array.

``````count=\${#ARRAY[@]}

lsearch()
{
status=-1

for((i=0;i<count;i++))
do
Temp=\$1

if [[ \$Temp -eq \${ARRAY[i]} ]]
then
status=0
searches=\$((i+1))
return
fi
done
}
``````

Suppose I need to look for all the elements of an array say `(a b c d)` in another array `( a h c d l k)`.

Now for each element in one array I need to loop over the other array with a for loop. Is there any better way?

• Do you need to look up values frequently? If so, you could create an associative array with the reversed key-value pairs of the second array. pastebin.com/TDuG4Av8 – manatwork Aug 13 '13 at 9:40
• Are there constraints on the array elements, or can they be arbitrary strings? – Gilles Aug 13 '13 at 23:04
• they can be arbitrary strings but unique – munish Aug 20 '13 at 7:33

## 1 Answer

If you don't want to loop through each entry of the second array for each value in the first, then you'll need to use an associative array. In awk you could do this:

``````\$ a=(a b c d);
\$ b=(a h c d l k);
\$ awk 'BEGIN{RS = FS} NR == FNR {a[\$1] = 1; next} \$1 in a' \
<(echo "\${a[*]}") <(echo "\${b[*]}")
a
c
d
``````

Pure bash would look something like this (although it is a little unwieldy.:

``````declare -A a
a=([a]=1 [b]=1 [c]=1 [d]=1)
declare -A b
b=([a]=1 [h]=1 [c]=1 [d]=1 [l]=1 [k]=1)
for i in \${!a[*]}; do
if [ ! -z "\${b[\$i]}" ]; then
echo "\$i is in both";
fi;
done
``````