一尘不染

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

linux

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

阅读 580

收藏
2020-06-07

共1个答案

一尘不染

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

2020-06-07