我在Bash中有一个字符串:
string="My string"
如何测试它是否包含另一个字符串?
if [ $string ?? 'foo' ]; then
echo "It's there!"
fi
哪里是我不认识的接线员。我使用echo和grep吗?
if echo "$string" | grep 'foo'; then
echo "It's there!"
fi
这看起来有点笨拙。
我在Bash中有一个字符串:
string="My string"
如何测试它是否包含另一个字符串?
if [ $string ?? 'foo' ]; then
echo "It's there!"
fi
哪里是我不认识的接线员。我使用echo和grep吗?
if echo "$string" | grep 'foo'; then
echo "It's there!"
fi
这看起来有点笨拙。
当前回答
我喜欢sed。
substr="foo"
nonsub="$(echo "$string" | sed "s/$substr//")"
hassub=0 ; [ "$string" != "$nonsub" ] && hassub=1
编辑,逻辑:
使用sed从字符串中删除子字符串的实例如果新字符串与旧字符串不同,则存在子字符串
其他回答
case $string in (*foo*)
# Do stuff
esac
这与https://stackoverflow.com/a/229585/11267590.但风格简单,也符合POSIX。
我不确定是否使用if语句,但您可以使用case语句获得类似的效果:
case "$string" in
*foo*)
# Do stuff
;;
esac
[[ $string == *foo* ]] && echo "It's there" || echo "Couldn't find"
如果使用双括号,也可以在case语句外使用Marcus的答案(*通配符):
string='My long string'
if [[ $string == *"My long"* ]]; then
echo "It's there!"
fi
注意,针字符串中的空格需要放在双引号之间,*通配符应该放在外面。还要注意,使用了简单的比较运算符(即==),而不是正则表达式运算符=~。
试试oobash。
它是Bash 4的OO风格字符串库。它支持德语元音变音。它是用巴什语写的。
有许多函数可用:-base64Decode、-base64Encode、-acapital、-center、-charAt、concat、-concontains、-count、-endsWith、-equals、-equalsIgnoreCase、-reverse、-hashCode、-indexOf、-isAlnum、-isAlpha、-isAscii、-isDigit、-isEmpty、-isHexDigit、-isLowerCase、-isSpace、-isPrintable、-isUpperCase、-isVisible、-lastIndexOf、-length、-matches、-replaceAll、-replaceFirst、-startsWith,-substring、-swapCase、-toLowerCase、-toString、-toUpperCase、-trim和-zfill。
查看包含的示例:
[Desktop]$ String a testXccc
[Desktop]$ a.contains tX
true
[Desktop]$ a.contains XtX
false
oobash可在Sourceforge.net上获得。