gpt4 book ai didi

linux - bash 中多个单词作为可能的变量

转载 作者:太空宇宙 更新时间:2023-11-04 04:41:20 25 4
gpt4 key购买 nike

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

但这会太长。

最佳答案

如果您的目标是 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 兼容。

关于linux - bash 中多个单词作为可能的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25233646/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com