bash:在多个其他字符串中查找字符串

时间:2013-07-17 22:17:09

标签: string bash list search

我正在尝试使用bash来查找任何字符串“sets”中是否存在短字符串。 例如,

FRUIT="apple banana kiwi melon"
VEGETABLE="radish lettuce potato"
COLOR="blue red yellow green brown"

MY_CHOICE="kiwi"
MY_CHOICE_GROUP="?"

如何将MY_CHOICE_GROUP设为FRUIT

我尝试使用this StackOverflow solution,但它仅适用于单个字符串集。

最初,我使用数组来存储集合中的选项,但是given the way bash handles iteration over arrays,似乎字符串搜索会更有效率。

非常感谢!

3 个答案:

答案 0 :(得分:5)

  1. IMO最简单的方法就是硬编码一堆case...esac标签。

    #!/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
    

    查看 live on ideone

  2. 否则,请考虑关联数组,请参阅 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
    

答案 1 :(得分:1)

只是缩短了一点@ sehe的答案:

#!/bin/bash

declare -A groups
mkaso() { val="$1"; shift; for key in "$@"; do groups["$key"]="$val"; done; }

mkaso FRUIT apple banana kiwi melon
mkaso VEGETABLE radish lettuce potato
mkaso COLOR blue red yellow green brown
#declare -p groups

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

答案 2 :(得分:1)

#!/bin/bash
FRUIT="apple banana kiwi melon"
VEGETABLE="radish lettuce potato"
COLOR="blue red yellow green brown"

MY_CHOICE="kiwi"

for group in VEGETABLE COLOR FRUIT
do
    if [[ ${!group} == *${MY_CHOICE}* ]]; then
        MY_CHOICE_GROUP=$group
        break
    fi
done

echo $MY_CHOICE_GROUP