我在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_profile文件以及我如何使用grep:

如果PATH环境变量包含我的两个bin目录,请不要追加它们,

# .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

U=~/.local.bin:~/bin

if ! echo "$PATH" | grep -q "home"; then
    export PATH=$PATH:${U}
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
}

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

#!/bin/bash

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

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

这也适用于:

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特性慢得多,因为将创建一个(或两个)单独的进程并通过管道连接。

我发现我经常需要这个功能,所以我在.bashrc中使用了一个自制的shell函数,这样我就可以随时重用它,并使用一个容易记住的名字:

function stringinstring()
{
    case "$2" in
       *"$1"*)
          return 0
       ;;
    esac
    return 1
}

要测试$string1(例如,abc)是否包含在$string2(例如,123abcABC)中,我只需要运行striginstring“$string1”“$string2”并检查返回值,例如

stringinstring "$str1" "$str2"  &&  echo YES  ||  echo NO
[[ $string == *foo* ]] && echo "It's there" || echo "Couldn't find"