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?

1

2 Answers 2

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
1

How about

for FN in ${first_list[@]}; do [[ ${second_list[@]} =~ $FN ]] && third_list+=($FN); done
1
  • 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. Commented Jan 16, 2019 at 7:43

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.