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

时间:2018-05-31 18:53:39

标签: string bash variables

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

  

一个,两个,三个

我的代码:

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

EDIT2:

我尝试了这个,但仍然不匹配。你是否正确它不匹配以前答案的确切字符串,因为它匹配部分。

 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

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

3 个答案:

答案 0 :(得分:1)

可能存在其他问题(例如匹配部分字词),但如果您使用=~(匹配)代替==,则可以用于简单案例

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

答案 1 :(得分:1)

其他答案存在一个问题,即他们会将列表中项目的部分的匹配视为匹配,例如if var1= admin,\ ndev,\ nstage (which I think is what you actually have), then it'll match if var is "e" or "min", or a bunch of other things. I'd recommend either removing the newlines from the variable (maybe by adding | tr -d'\ n'`到创建它的管道的末尾),并使用:

if [[ ",${var}," = *",${var1},"* ]]; then

$var周围的逗号将其锚定到项目的开头和结尾,$var1周围的逗号允许它为第一个和最后一个项目添加字词。)您也可以使其工作在$var1中留下了换行符,但这就是那种迟早会让你搞砸的事情。

答案 2 :(得分:0)

这样的东西?

#!/bin/bash
echo "please enter one,two or three"
read var

var1=["one","two","three"]


if [[ ${var} = *${var1}* ]]; then
    echo "${var} is in the list"
else
    echo "${var} is not in the list"
fi
相关问题