Bash 检查字符串是否不包含其他字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30557508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash checking if string does not contain other string
提问by machinery
I have a string ${testmystring}
in my .shscript and I want to check if this string does not contain another string.
${testmystring}
我的.sh脚本中有一个字符串,我想检查这个字符串是否不包含另一个字符串。
if [[ ${testmystring} doesNotContain *"c0"* ]];then
# testmystring does not contain c0
fi
How can I do that, i.e. what is doesNotContain supposed to be?
我怎么能做到这一点,即doesNotContain 应该是什么?
回答by cychoi
Use !=
.
使用!=
.
if [[ ${testmystring} != *"c0"* ]];then
# testmystring does not contain c0
fi
See help [[
for more information.
有关help [[
更多信息,请参阅。
回答by Roberto De Oliveira
As mainframer said, you can use grep, but i would use exit status for testing, try this:
正如大型机所说,你可以使用 grep,但我会使用退出状态进行测试,试试这个:
#!/bin/bash
# Test if anotherstring is contained in teststring
teststring="put you string here"
anotherstring="string"
echo ${teststring} | grep --quiet "${anotherstring}"
# Exit status 0 means anotherstring was found
# Exit status 1 means anotherstring was not found
if [ $? = 1 ]
then
echo "$anotherstring was not found"
fi
回答by Thiago Conrado
Bash allow u to use =~ to test if the substring is contained. Ergo, the use of negate will allow to test the opposite.
Bash 允许您使用 =~ 来测试是否包含子字符串。因此,使用 negate 将允许进行相反的测试。
fullstring="123asdf123"
substringA=asdf
substringB=gdsaf
# test for contains asdf, gdsaf and for NOT CONTAINS gdsaf
[[ $fullstring =~ $substring ]] && echo "found substring $substring in $fullstring"
[[ $fullstring =~ $substringB ]] && echo "found substring $substringB in $fullstring" || echo "failed to find"
[[ ! $fullstring =~ $substringB ]] && echo "did not find substring $substringB in $fullstring"