edumike edumike - 4 months ago 21
Linux Question

How to find substring inside a string (or how to grep a variable)?

I'm using BASH, and I don't know how to find a substring. It keeps failing, I've got a string (should this be an array?)

Below,

LIST
is a string list of database names,
SOURCE
is the reply, one of those databases. The following still doesn't work:

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


I've also tried this but doesn't work:

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

Answer
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
Comments