如何在字符串中找到子字符串(或如何grep变量)?

edu*_*ike 28 linux string db2 bash

我正在使用BASH,我不知道如何找到子串.它一直都失败了,我有一个字符串(这应该是一个数组吗?)

下面LIST是数据库名称的字符串列表,SOURCE是回复,其中一个数据库.以下仍然不起作用:

echo "******************************************************************"
echo "*                  DB2 Offline Backup Script                     *"
echo "******************************************************************"
echo "What's the name of of the  database you would like to backup?"
echo "It will be named one in this list:"
echo ""
LIST=`db2 list database directory | grep "Database alias" | awk '{print $4}'`
echo $LIST
echo ""
echo "******************************************************************"
echo -n ">>> "
read -e SOURCE

if expr match "$LIST" "$SOURCE"; then
    echo "match"
    exit -1
else
    echo "no match"
fi
exit -1
Run Code Online (Sandbox Code Playgroud)

我也试过这个但是不行:

if [ `expr match "$LIST" '$SOURCE'` ]; then
Run Code Online (Sandbox Code Playgroud)

die*_*dha 54

LIST="some string with a substring you want to match"
SOURCE="substring"
if echo "$LIST" | grep -q "$SOURCE"; then
  echo "matched";
else
  echo "no match";
fi
Run Code Online (Sandbox Code Playgroud)


sre*_*mer 30

您还可以与通配符进行比较:

if [[ "$LIST" == *"$SOURCE"* ]]

  • 你应该总是引用字符串,例如:`if [["$ list"==*"$ source"*]]` (7认同)

Sor*_*gal 7

如果你正在使用bash,你可以说

if grep -q "$SOURCE" <<< "$LIST" ; then
    ...
fi
Run Code Online (Sandbox Code Playgroud)


His*_*H M 6

这适用于Bash而不需要外部命令:

function has_substring() {
   [[ "$1" != "${2/$1/}" ]]
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

name="hello/world"
if has_substring "$name" "/"
then
   echo "Indeed, $name contains a slash!"
fi
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这是使用正则表达式来搜索子字符串(并且还会进行异地替换),因此搜索(子字符串)中的特殊字符可能会导致意外结果。但是如果正则表达式很好,那么为什么不直接进行正则表达式搜索(即不需要替换)?语法示例:if [[ "$string" =~ $substring ]] (4认同)