我在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
这看起来有点笨拙。
当前回答
由于POSIX/BusyBox问题在没有提供正确答案(IMHO)的情况下结束,我将在这里发布答案。
最简单的答案是:
[ ${_string_##*$_substring_*} ] || echo Substring found!
or
[ "${_string_##*$_substring_*}" ] || echo 'Substring found!'
注意,对于某些shell(ash),双哈希是必须的。当未找到子字符串时,上面将计算[stringvalue]。它不会返回错误。找到子字符串时,结果为空,其结果为[]。这将抛出错误代码1,因为字符串被完全替换(由于*)。
最短最常见的语法:
[ -z "${_string_##*$_substring_*}" ] && echo 'Substring found!'
or
[ -n "${_string_##*$_substring_*}" ] || echo 'Substring found!'
另一个:
[ "${_string_##$_substring_}" != "$_string_" ] && echo 'Substring found!'
or
[ "${_string_##$_substring_}" = "$_string_" ] || echo 'Substring found!'
注意单个等号!
其他回答
grep-q对于这个目的很有用。
同样使用awk:
string="unix-bash 2389"
character="@"
printf '%s' "$string" | awk -vc="$character" '{ if (gsub(c, "")) { print "Found" } else { print "Not Found" } }'
输出:
未找到
string="unix-bash 2389"
character="-"
printf '%s' "$string" | awk -vc="$character" '{ if (gsub(c, "")) { print "Found" } else { print "Not Found" } }'
输出:
建立
原始来源:http://unstableme.blogspot.com/2008/06/bash-search-letter-in-string-awk.html
由于POSIX/BusyBox问题在没有提供正确答案(IMHO)的情况下结束,我将在这里发布答案。
最简单的答案是:
[ ${_string_##*$_substring_*} ] || echo Substring found!
or
[ "${_string_##*$_substring_*}" ] || echo 'Substring found!'
注意,对于某些shell(ash),双哈希是必须的。当未找到子字符串时,上面将计算[stringvalue]。它不会返回错误。找到子字符串时,结果为空,其结果为[]。这将抛出错误代码1,因为字符串被完全替换(由于*)。
最短最常见的语法:
[ -z "${_string_##*$_substring_*}" ] && echo 'Substring found!'
or
[ -n "${_string_##*$_substring_*}" ] || echo 'Substring found!'
另一个:
[ "${_string_##$_substring_}" != "$_string_" ] && echo 'Substring found!'
or
[ "${_string_##$_substring_}" = "$_string_" ] || echo 'Substring found!'
注意单个等号!
我不确定是否使用if语句,但您可以使用case语句获得类似的效果:
case "$string" in
*foo*)
# Do stuff
;;
esac
因此,这个问题有很多有用的解决方案——但哪一个最快/使用的资源最少?
使用此框架重复测试:
/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是可想而知的痛苦!关于无需使用外部实用程序的旧规则是正确的。
通用的大海捞针示例下面是变量
#!/bin/bash
needle="a_needle"
haystack="a_needle another_needle a_third_needle"
if [[ $haystack == *"$needle"* ]]; then
echo "needle found"
else
echo "needle NOT found"
fi