如何查找字符串中的子字符串(或如何grep变量)?

我正在使用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

我也试过这个,但不起作用:

if [ `expr match "$LIST" '$SOURCE'` ]; then

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

你也可以比较通配符:

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


如果你使用bash,你可以说

if grep -q "$SOURCE" <<< "$LIST" ; then
    ...
fi
链接地址: http://www.djcxy.com/p/36197.html

上一篇: How to find substring inside a string (or how to grep a variable)?

下一篇: String comparison in bash. [[: not found