string - 使用 if 语句在变量中查找字符串

标签 string bash variables

<分区>

我目前正试图在一个输出如下内容的变量中找到一个字符串:

one,two,three

我的代码:

echo "please enter one,two or three)
read var

var1=one,two,threee

if [[ "$var" == $var1 ]]; then
    echo "$var is in the list"
else
    echo "$var is not in the list"
fi

编辑2:

我试过了,还是不匹配。你是正确的,它不匹配以前答案中的确切字符串,因为它匹配部分。

 groups="$(aws iam list-groups --output text | awk '{print tolower($5)}' | sed '$!s/$/,/' | tr -d '\n')"
echo "please enter data"
read "var"

if [ ",${var}," = *",${groups},"* ]; then
    echo "$var is in the list"
else
    echo "$var is not in the list"
fi

尝试这个仍然没有匹配我需要的确切字符串。

最佳答案

可能还有其他问题(比如匹配部分单词),但是如果您使用 =~ (匹配)而不是 == 它会适用于简单的情况

if [[ "$var1" =~ "$var" ]]; then
   ...

关于string - 使用 if 语句在变量中查找字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50630981/

相关文章:

bash - 在 cloudformation 中运行 Bash 命令

php - 如何将表单查询插入 $html = file_get_contents_curl();

c++ - 通过串行读取 utf8 时,Arduino 表现异常

java - string.replaceAll 替换出现的地方

bash - 在什么情况下,文件通配符在 bash 中不起作用?

bash - bash脚本上的错误处理

c++ - std::string 和 placement new

string - swift 2 : Iterating and upper/lower case some characters

PHP动态访问变量值

c# - 是否可以在变量名的名称中使用变量号?