I want to have a function that reports all strings, across two arrays, that are identical to one another.
ARRAY_A=("table" "dog" "bird" "caterpillar")
ARRAY_B=("cup" "door" "table" "cat")
for VALUE_B in "${ARRAY_B[@]}"
do
[[ "${ARRAY_A[@]}" =~ ${VALUE_B} ]] && echo ${VALUE_B} is in both arrays
This returns the output:
table is in both arrays
cat is in both arrays
The code is finding 'cat' in 'caterpillar' and returning that 'cat is in both arrays'. I only want the code to return 'cat is in both arrays' if the string is identical in both arrays ('cat':'cat').
While I could add in a nested for loop to go through and compare each value of ARRAY_A to each value in ARRAY_B, this solution would be inefficient on a larger scale. I believe there is a more efficient solution to this problem that I haven't realized yet.
Additionally,
I'd be willing to settle for a solution which checks if there are any strings in ARRAY_A that end with a value from ARRAY_B (bobcat:cat). This has led me to try out the following modification to the code above:
[[ "${ARRAY_A[@]}" =~ ${VALUE_B}$ ]] && echo $VALUE_B is in both arrays
However, it only compares the values of ARRAY_B to the end of ARRAY_A as a whole, not the individual values of ARRAY_A. Again, this could be solved with a nested for loop, but I believe there is a better solution that will work more effectively at scale.