0

Say I have these two "lists":

#!/usr/bin/env bash

git fetch origin;

first_list=( );
second_list=( );

git branch --merged "remotes/origin/dev" | tr -d ' *' | while read branch; do
     first_list+=( "$branch" );
done


git branch --merged HEAD | tr -d ' *' | while read branch; do
     second_list+=( "$branch" );
done

I need to create a third list that holds the intersection of elements in the first and second lists. How can I do that?

2 Answers2

2

Using an associative array as a helper to keep track of the elements in one list (as keys), and then quickly checking the elements of the other list against these:

#!/bin/bash

list1=( 1 3 5 6 7 8 bumble bee )
list2=( 2 4 4 4 6 7 8 bee beer )

declare -A seen

for item in "${list1[@]}"; do
    seen[$item]=1
done

for item in "${list2[@]}"; do
    if [ -n "${seen[$item]}" ]; then
        intersection+=( "$item" )
    fi
done

echo 'Intersection:'
printf '\t%s\n' "${intersection[@]}"

This uses exact string matches to compare the elements between the two lists.

Result:

Intersection:
    6
    7
    8
    bee
Kusalananda
  • 333,661
1

How about

for FN in ${first_list[@]}; do [[ ${second_list[@]} =~ $FN ]] && third_list+=($FN); done
RudiC
  • 8,969
  • This will break if any list contains an element with whitespaces, and it looks like it would also match substrings of items in the first list in the second. – Kusalananda Jan 16 '19 at 07:43