我在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 printf -- '%s' "$haystack" | egrep -q -- "$needle"
then
  printf "Found needle in haystack"
fi

阴性试验为:

if ! printf -- '%s' "$haystack" | egrep -q -- "$needle"
then
  echo "Did not find needle in haystack"
fi

我认为这种风格更为经典——更少依赖于Bash shell的特性。

--参数是纯粹的POSIX偏执狂,用于防止类似于选项的输入字符串,例如--abc或-a。

注意:在紧密循环中,此代码将比使用内部Bashshell特性慢得多,因为将创建一个(或两个)单独的进程并通过管道连接。

其他回答

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

string='My string';

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

这个怎么样:

text="   <tag>bmnmn</tag>  "
if [[ "$text" =~ "<tag>" ]]; then
   echo "matched"
else
   echo "not matched"
fi

这里回答的问题的扩展如何判断POSIX sh中的字符串是否包含另一个字符串?:

此解决方案适用于特殊字符:

# contains(string, substring)
#
# Returns 0 if the specified string contains the specified substring,
# otherwise returns 1.
contains() {
    string="$1"
    substring="$2"

    if echo "$string" | $(type -p ggrep grep | head -1) -F -- "$substring" >/dev/null; then
        return 0    # $substring is in $string
    else
        return 1    # $substring is not in $string
    fi
}

contains "abcd" "e" || echo "abcd does not contain e"
contains "abcd" "ab" && echo "abcd contains ab"
contains "abcd" "bc" && echo "abcd contains bc"
contains "abcd" "cd" && echo "abcd contains cd"
contains "abcd" "abcd" && echo "abcd contains abcd"
contains "" "" && echo "empty string contains empty string"
contains "a" "" && echo "a contains empty string"
contains "" "a" || echo "empty string does not contain a"
contains "abcd efgh" "cd ef" && echo "abcd efgh contains cd ef"
contains "abcd efgh" " " && echo "abcd efgh contains a space"

contains "abcd [efg] hij" "[efg]" && echo "abcd [efg] hij contains [efg]"
contains "abcd [efg] hij" "[effg]" || echo "abcd [efg] hij does not contain [effg]"

contains "abcd *efg* hij" "*efg*" && echo "abcd *efg* hij contains *efg*"
contains "abcd *efg* hij" "d *efg* h" && echo "abcd *efg* hij contains d *efg* h"
contains "abcd *efg* hij" "*effg*" || echo "abcd *efg* hij does not contain *effg*"

正如Paul在绩效比较中提到的:

if echo "abcdefg" | grep -q "bcdef"; then
    echo "String contains is true."
else
    echo "String contains is not true."
fi

这是符合POSIX的,就像Marcus提供的答案中的“case“$string”一样,但它比case语句答案更容易阅读。还要注意,这将比使用case语句慢得多。正如保罗所指出的,不要在循环中使用它。

您应该记住,shell脚本不是一种语言,而是一组命令。你本能地认为这种“语言”要求你在if后面加一个[或一个[[。这两个命令都只是返回一个表示成功或失败的退出状态的命令(就像其他所有命令一样)。出于这个原因,我会使用grep,而不是[命令。

只要做到:

if grep -q foo <<<"$string"; then
    echo "It's there"
fi

既然您正在考虑如果测试它后面的命令的退出状态(用分号完成),为什么不重新考虑您正在测试的字符串的源代码?

## Instead of this
filetype="$(file -b "$1")"
if grep -q "tar archive" <<<"$filetype"; then
#...

## Simply do this
if file -b "$1" | grep -q "tar archive"; then
#...

-q选项使grep不输出任何内容,因为我们只需要返回代码使shell展开下一个单词,并将其用作命令的输入,这是<<here文档的一行版本(我不确定这是标准还是巴什主义)。