bash: find string in multiple other strings

bash, list, search, string

Solution

The simplest way, IMO, would be to just hardcode a bunch of `case...esac` labels.

#!/bin/bash
function lookup()
{
    case "$1" in
        apple|banana|kiwi|melon)
            echo "FRUIT"
            ;;

        radish|lettuce|potato)  
            echo "VEGETABLE"
            ;;

        blue|red|yellow|green|brown)   
            echo "COLOR"
            ;;
    esac
}

MY_CHOICE="kiwi"
MY_CHOICE_GROUP=$(lookup "$MY_CHOICE")

echo $MY_CHOICE: $MY_CHOICE_GROUP

See it live on ideone

Otherwise, consider associative arrays, see it live on ideone:

#!/bin/bash
declare -A groups

groups["apple"]="FRUIT"
groups["banana"]="FRUIT"
groups["kiwi"]="FRUIT"
groups["melon"]="FRUIT"

groups["radish"]="VEGETABLE"
groups["lettuce"]="VEGETABLE"
groups["potato"]="VEGETABLE"

groups["blue"]="COLOR"
groups["red"]="COLOR"
groups["yellow"]="COLOR"
groups["green"]="COLOR"
groups["brown"]="COLOR"

MY_CHOICE="kiwi"
MY_CHOICE_GROUP=${groups[$MY_CHOICE]}

echo $MY_CHOICE: $MY_CHOICE_GROUP

Problem

I'm trying to use bash to find if a short string is present in any string "sets". For example, ``` FRUIT="apple banana kiwi melon" VEGETABLE="radish lettuce potato" COLOR="blue red yellow green brown" MY_CHOICE="kiwi" MY_CHOICE_GROUP="?" ``` How can I set `MY_CHOICE_GROUP` to `FRUIT`? I tried to use this StackOverflow solution, but it only works with a single string set. Originally, I was using arrays to store the options in a set, but given the way bash handles iteration over arrays, it seems a string search would be more efficient. Many thanks!

Original source

Related problems