Finding a string in a varaible with if statement
本问题已经有最佳答案,请猛点这里访问。
我目前正试图在一个变量中找到一个字符串,该变量输出如下:
one,two,three
我的代码:
1 2 3 4 5 6 7 8 9 10 | 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:
我试过了,但还是不匹配。你说得对,它与之前答案中的确切字符串不匹配,因为它是部分匹配的。
1 2 3 4 5 6 7 8 9 10 | groups="$(aws iam list-groups --output text | awk '{print tolower($5)}' | sed '$!s/$/,/' | tr -d ' ')" 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 |
尝试这个,它仍然不匹配确切的字符串,因为我需要它。
其他答案存在一个问题,即他们会将列表中某项的部分匹配项视为匹配项,例如,如果
1 | if [[",${var}," = *",${var1},"* ]]; then |
(围绕
可能还有其他问题(比如匹配部分单词),但是如果使用
1 2 | if [["$var1" =~"$var" ]]; then ... |
像这样?
1 2 3 4 5 6 7 8 9 10 11 12 | #!/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 |