2

i have two array of numbers, first array have all numbers while the second has a subset of first one, how can i write a script to find the missing number which exist in the first array but not in the second array?

Array 1: [0, 1, 2, ..79] Array 2: [1, 12, 33, 54,60, 71]

i googled around and tried different approaches i found but none of them worked

1.

declare -a array3
for i in "${array1[@]}"
  if [[ "${array2[@]}" =~ "$i" || "${array2[${#array2[@]}-1]}" == "$i" ]]; then
  else
      array3+=("$i") 
  fi
done

2.

array3=()
for i in "${array1[@]}";do
  skip=
  for j in "$array2[@]";do
     [[ $i == $j ]] && { skip=1; break; }
  done
  [[ -n $skip ]] || array3+=("$i")
done
declare -p array3

i m new to bash script, please help!

1
  • Are the elements in each array sorted? If so, you'll need to run a loop with, say, index $i for array1 and $j for array2, and you will either find that $array1[$i] is smaller than $array2[$j, or equal to it, or larger than it. If the number in $array1[$i] is smaller, print it and increment $i; if the values are equal, increment both $i and $j; if it is larger, increment $j. Stop when you reach the end of either array. Commented Mar 6, 2015 at 16:58

1 Answer 1

4

One way to get array differential is using comm:

array1=(0 1 2 3 4 5 6 7 8 9 10 11 12)
array2=(0 1 3 4 6 7 10 12)

comm -23 <(printf "%s\n" "${array1[@]}" | sort) <(printf "%s\n" "${array2[@]}" | sort) | sort -n

2
5
8
9
11
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.