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

这看起来有点笨拙。


当前回答

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

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

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

其他回答

一个是:

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

这个怎么样:

text="   <tag>bmnmn</tag>  "
if [[ "$text" =~ "<tag>" ]]; then
   echo "matched"
else
   echo "not matched"
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上获得。

您可以使用逻辑&&以更紧凑

#!/bin/bash

# NO MATCH EXAMPLE
string="test"
[[ "$string" == *"foo"* ]] && {
        echo "YES"
}

# MATCH EXAMPLE
string="tefoost"
[[ "$string" == *"foo"* ]] && {
        echo "YES"
}

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