Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 
like image 992
edumike Avatar asked Dec 17 '10 04:12

edumike


People also ask

How do you grep on a variable?

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.

How do you find if a string contains a substring in shell script?

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 .


1 Answers

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 
like image 59
dietbuddha Avatar answered Oct 06 '22 04:10

dietbuddha