-1

Hi=("Hi" "Hello" "Hey")行有可能的输入。我尝试在单词之间添加逗号,但这也不起作用。如果输入了hihellohey,我需要它来回显“Hi”。现在只有Hi有效。我想我正在寻找的是一种为一个词制作“同义词”的方法。用一个词代替另一个词的能力。

    clear; echo
    shopt -s nocasematch
    echo; read -p "    > " TextInput

    Hi=("Hi" "Hello" "Hey")

     if [[ "$TextInput" == $Hi ]]; then
    clear; echo; echo
    echo -e "    >> Hi"
    echo

     else
    clear; echo; echo
    echo -e "    >> Error"
    echo
    fi

我知道我可以使用

     if [[ "$TextInput" == "Hi" ]] || [[ "$TextInput" == "Hello" ]] || [[ "$TextInput" == "Hey" ]]; then

但这将变得太长了。

4

4 回答 4

2

如果您的目标是 bash 4.0 或更高版本,则关联数组将起作用:

TextInput=Hello
declare -A values=( [Hi]=1 [Hello]=1 [Hey]=1 )

if [[ ${values[$TextInput]} ]]; then
  echo "Hi there!"
else
  echo "No Hi!"
fi

这是一个 O(1) 查找,使其比基于 O(n) 循环的遍历更快。


也就是说,如果您要匹配的项目列表是硬编码的,只需使用 case 语句:

case $TextInput in
  Hi|Hello|Hey) echo "Hi there!" ;;
  *)            echo "No Hi!     ;;
esac

这还具有与任何符合 POSIX sh 的 shell 兼容的优点。

于 2014-08-10T23:11:20.567 回答
1

看看这个变种:

TextInput="Hello"
Hi=("Hi" "Hello" "Hey")

flag=0

for myhi in ${Hi[@]}; do
    if [[ "$TextInput" == "$myhi" ]]; then
        flag=1
        break
    fi
done

if [[ $flag == 1 ]]; then
    echo "Hi there!"
else
    echo "No Hi!"
fi

问题是:使用标志+ for 循环。如果设置了标志 (=1),则TextInput等于Hi数组中的某个值。

于 2014-08-10T22:39:08.350 回答
0

根据您的需要,您还可以使用开关:

case "$input" in
  "Hi"|"He"*)
    echo Hello
    ;;
  *)
    echo Error
    ;;
  esac

这还允许您指定模式。

于 2014-08-10T23:19:04.853 回答
0

使用 bash 的模式匹配:

$ Hi=(Hi Hello Hey)
$ input=foo
$ if (IFS=:; [[ ":${Hi[*]}:" == *:"$input":* ]]); then echo Y; else echo N; fi
N
$ input=Hey
$ if (IFS=:; [[ ":${Hi[*]}:" == *:"$input":* ]]); then echo Y; else echo N; fi
Y

我在这里使用括号来生成一个子shell,因此对 IFS 变量的更改不会影响当前的 shell。

于 2014-08-11T00:09:17.843 回答