我在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

这看起来有点笨拙。


当前回答

精确的单词匹配:

string='My long string'
exactSearch='long'

if grep -E -q "\b${exactSearch}\b" <<<${string} >/dev/null 2>&1
  then
    echo "It's there"
  fi

其他回答

如果您喜欢正则表达式方法:

string='My string';

if [[ $string =~ "My" ]]; then
   echo "It's there!"
fi

一个是:

[ $(expr $mystring : ".*${search}.*") -ne 0 ] && echo 'yes' ||  echo 'no'

此堆栈溢出答案是唯一一个陷阱空格和破折号字符的答案:

# For null cmd arguments checking   
to_check=' -t'
space_n_dash_chars=' -'
[[ $to_check == *"$space_n_dash_chars"* ]] && echo found

通用的大海捞针示例下面是变量

#!/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

公认的答案是最好的,但由于有不止一种方法可以做到这一点,这里有另一种解决方案:

if [ "$string" != "${string/foo/}" ]; then
    echo "It's there!"
fi

${var/search/replace}是$var,如果找到了第一个搜索实例,则将其替换为replace(它不会更改$var)。如果您试图将foo替换为空,并且字符串发生了更改,那么很明显找到了foo。