Bash: How to Find the Intersection of Two Arrays


Often you may want to find the intersection of two arrays in Bash, i.e. the values that the two arrays have in common.

You can use the following syntax to do so:

echo "${array1[@]} ${array2[@]}" | sed 's/ /\n/g' | sort | uniq -d

This particular example returns the values that belong to both arrays named array1 and array2.

Here is what the various commands do:

  • echo “${array1[@]} ${array2[@]}”: Prints all elements from both arrays
  • sed ‘s/ /\n/g’: Replaces each space with a newline so that all elements from both arrays are shown on individual lines
  • sort: Sorts all elements from both arrays
  • uniq -d: Returns only unique elements that have duplicate values

The following example shows how to use this syntax in practice.

Example: How to Find Intersection of Two Arrays in Bash

Suppose that we create the following two arrays named array1 and array2 in Bash that contain the names of various basketball teams:

array1=(Mavs Warriors Celtics Nets Hawks Kings)
array2=(Celtics Nuggets Lakers Mavs Spurs)

Suppose that we would like to find the team names that belong in both arrays, i.e. the intersection of the two arrays.

We can use the following syntax to do so:

echo "${array1[@]} ${array2[@]}" | sed 's/ /\n/g' | sort | uniq -d

The following screenshot shows how to use this syntax in practice:

Bash find intersection of two arrays

Note that this returns the following team names:

  • Celtics
  • Mavs

Both of these team names appear in both arrays.

Thus, these two teams represent the intersection between the two arrays.

Feel free to use similar syntax to find the intersection of your own two arrays in Bash.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Generate Random Number in Range
Bash: How to Select Random Lines from a File
Bash: How to Select Random Files from Directory

Leave a Reply