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
Counting the Instances of a String in a Variable You can use the wc utility to count the number of times a string is found in a variable. To do this, you must first tell grep to only show the matching characters with the -o (--only-matching) option. Then you can pipe it to wc.
Using Regex Operator Another option to determine whether a specified substring occurs within a string is to use the regex operator =~ . When this operator is used, the right string is considered as a regular expression. The period followed by an asterisk .
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With