-1

I have a text file in the following format:

A Apple

A Ant

B Bat

B Ball

The number of definitions of each character can be any number.

I am writing a shell script which will receive inputs like "A B". The output of the shell script I am expecting is the possible string sequences which can be created.

For input "A B", the outputs will be:

Apple Bat

Apple Ball

Ant Bat

Ant Ball

I tried arrays, It is not working as expected. Can anyone help with some ideas on how to solve this issue?

AKA
  • 5,479
  • 4
  • 22
  • 36

1 Answers1

0

Use associative arrays to accomplish this:

#!/usr/bin/env bash

first_letter=$1
second_letter=$2

declare -A words                  # declare associative array
while read -r alphabet word; do   # read ignores blank lines in input file
  words+=(["$word"]="$alphabet")  # key = word, value = alphabet
done < words.txt

for word1 in "${!words[@]}"; do
  alphabet1="${words[$word1]}"
  [[ $alphabet1 != $first_letter ]] && continue
  for word2 in "${!words[@]}"; do
    alphabet2="${words[$word2]}"
    [[ $alphabet2 != $second_letter ]] && continue
    printf "$word1 $word2\n"              # print matching word pairs
  done
done

Output with A B passed in as arguments (with the content in your question):

Apple Ball
Apple Bat
Ant Ball
Ant Bat

You may want to refer to this post for more info on associative arrays: Appending to a hash table in Bash

Community
  • 1
  • 1
codeforester
  • 39,467
  • 16
  • 112
  • 140