我在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
这看起来有点笨拙。
当前回答
因此,这个问题有很多有用的解决方案——但哪一个最快/使用的资源最少?
使用此框架重复测试:
/usr/bin/time bash -c 'a=two;b=onetwothree; x=100000; while [ $x -gt 0 ]; do TEST ; x=$(($x-1)); done'
每次更换测试:
[[ $b =~ $a ]] 2.92 user 0.06 system 0:02.99 elapsed 99% CPU
[ "${b/$a//}" = "$b" ] 3.16 user 0.07 system 0:03.25 elapsed 99% CPU
[[ $b == *$a* ]] 1.85 user 0.04 system 0:01.90 elapsed 99% CPU
case $b in *$a):;;esac 1.80 user 0.02 system 0:01.83 elapsed 99% CPU
doContain $a $b 4.27 user 0.11 system 0:04.41 elapsed 99%CPU
(doContain在F.Houri的回答中)
对于傻笑:
echo $b|grep -q $a 12.68 user 30.86 system 3:42.40 elapsed 19% CPU !ouch!
因此,无论是在扩展测试还是案例中,简单的替代选项都可以预测地获胜。这个箱子是便携式的。
输出到100000 greps是可想而知的痛苦!关于无需使用外部实用程序的旧规则是正确的。
其他回答
我不确定是否使用if语句,但您可以使用case语句获得类似的效果:
case "$string" in
*foo*)
# Do stuff
;;
esac
如果使用双括号,也可以在case语句外使用Marcus的答案(*通配符):
string='My long string'
if [[ $string == *"My long"* ]]; then
echo "It's there!"
fi
注意,针字符串中的空格需要放在双引号之间,*通配符应该放在外面。还要注意,使用了简单的比较运算符(即==),而不是正则表达式运算符=~。
我使用这个函数(一个不包括但很明显的依赖项)。它通过了以下测试。如果函数返回值>0,则找到字符串。你也可以很容易地返回1或0。
function str_instr {
# Return position of ```str``` within ```string```.
# >>> str_instr "str" "string"
# str: String to search for.
# string: String to search.
typeset str string x
# Behavior here is not the same in bash vs ksh unless we escape special characters.
str="$(str_escape_special_characters "${1}")"
string="${2}"
x="${string%%$str*}"
if [[ "${x}" != "${string}" ]]; then
echo "${#x} + 1" | bc -l
else
echo 0
fi
}
function test_str_instr {
str_instr "(" "'foo@host (dev,web)'" | assert_eq 11
str_instr ")" "'foo@host (dev,web)'" | assert_eq 19
str_instr "[" "'foo@host [dev,web]'" | assert_eq 11
str_instr "]" "'foo@host [dev,web]'" | assert_eq 19
str_instr "a" "abc" | assert_eq 1
str_instr "z" "abc" | assert_eq 0
str_instr "Eggs" "Green Eggs And Ham" | assert_eq 7
str_instr "a" "" | assert_eq 0
str_instr "" "" | assert_eq 0
str_instr " " "Green Eggs" | assert_eq 6
str_instr " " " Green " | assert_eq 1
}
公认的答案是最好的,但由于有不止一种方法可以做到这一点,这里有另一种解决方案:
if [ "$string" != "${string/foo/}" ]; then
echo "It's there!"
fi
${var/search/replace}是$var,如果找到了第一个搜索实例,则将其替换为replace(它不会更改$var)。如果您试图将foo替换为空,并且字符串发生了更改,那么很明显找到了foo。
如果您喜欢正则表达式方法:
string='My string';
if [[ $string =~ "My" ]]; then
echo "It's there!"
fi