Sollosa
Sollosa

Reputation: 431

How to iterate combinations of elements in two arrays in bash?

I have 2 different lists, I have separated these in 2 different files.

# cat file1

S1
S2
S3

and

# cat file2

R1
R2
R3

I want to loop over both files, so in first loop, S1 makes all possible cominations with elements in file2, like this

echo "First List Of Combinations"
echo S1 + R1
echo S1 + R2
echo S1 + R3

then second combinations

echo "Second List Of Combinations"
echo S2 + R1
echo S2 + R2
echo S2 + R3

So I decided to put these in two arrays.

arr1 = $(cat file1)
arr2 = $(cat file2)

what should I read first and what should be incremented? I know this will include 2 while loops reading elements from both arrays.

Upvotes: 0

Views: 1520

Answers (3)

Atlas Arizzen
Atlas Arizzen

Reputation: 21

Alternative to Arrays and Mapfiles, just 2 loops:

while read a  
do  
    while read b  
    do  
        echo $a + $b  
    done < file2  
done < file1  

Upvotes: 2

L&#233;a Gris
L&#233;a Gris

Reputation: 19545

Fixed answer of Bustkiller,

#!/usr/bin/env bash

# Properly reading file lines into arrays
mapfile -t arr1 <file1
mapfile -t arr2 <file2

# Iterating the index of arr1
for i in "${!arr1[@]}"
do
  # Properly formatted print-out of combination index with arr1 element
  printf 'List of combinations #%d\n' "$((i + 1))"

  # Iterating the index of arr2
  for j in "${!arr2[@]}"
  do
    # Properly formatting the combinations of elements from both arrays by index
    printf '%s + %s\n' "${arr1[i]}" "${arr2[j]}"
  done
done
# Properly formatting the total computed number of combinations that is:
# number of elements in array1 times number of elements in array2
printf 'Total number of combinations: %d\n' "$((${#arr1[@]} * ${#arr2[@]}))"

Upvotes: 3

Bustikiller
Bustikiller

Reputation: 2498

The following script should work:

#!/usr/bin/env bash

arr1=$(cat file1)
arr2=$(cat file2)

combinations_counter=1

for i in $arr1
do
  echo "List of combinations #$combinations_counter"
  for j in $arr2 
  do
    echo "$i + $j"
  done
  ((combinations_counter++))
done

With the file1 and file2 files provided, the result would be:

List of combinations #1
S1 + R1
S1 + R2
S1 + R3
List of combinations #2
S2 + R1
S2 + R2
S2 + R3
List of combinations #3
S3 + R1
S3 + R2
S3 + R3

Upvotes: 1

Related Questions