Issue
How do we compare two arrays and display the result in a shell script?
Suppose we have two arrays as below:
list1=( 10 20 30 40 50 60 90 100 101 102 103 104)
list2=( 10 20 30 40 50 60 70 80 90 100 )
My requirement is to compare these two arrays in an order that it will only display the result as (101 102 103 104)
from list1
. It should not include the values 70
and 80
which are present in list2
but not in list1
.
This does not help since it is including everything:
echo "${list1[@]}" "${list2[@]}" | tr ' ' '\n' | sort | uniq -u
I tried something like this below, but why is it not working?
list1=( 10 20 30 40 50 60 70 90 100 101 102 103 104)
list2=( 10 20 30 40 50 60 70 80 90 100 )
for (( i=0; i<${#list1[@]}; i++ )); do
for (( j=0; j<${#list2[@]}; j++ )); do
if [[ ${list1[@]} == ${list2[@] ]]; then
echo 0
break
if [[ ${#list2[@]} == ${#list1[@]-1} && ${list1[@]} != ${list2[@]} ]];then
echo ${list3[$i]}
fi
fi
done
done
Solution
Could also use this kind of approach
#!/bin/ksh
list1=( 10 20 30 40 50 60 90 100 101 102 103 104 )
list2=( 10 20 30 40 50 60 70 80 90 100 )
# Creating a temp array with index being the same as the values in list1
for i in ${list1[*]}; do
list3[$i]=$i
done
# If value of list2 can be found in list3 forget this value
for j in ${list2[*]}; do
if [[ $j -eq ${list3[$j]} ]]; then
unset list3[$j]
fi
done
# Print the remaining values
print ${list3[*]}
Output is
101 102 103 104
Hope it could help
EDIT
In case of the 2 list are the same :
# Print the remaining values
if [[ ${#list3[*]} -eq 0 ]]; then
print "No differences between the list"
else
print ${list3[*]}
fi
Answered By - Andre Gelinas Answer Checked By - Timothy Miller (WPSolving Admin)