MOHAMED
MOHAMED

Reputation: 43558

How to check if a string is a substring of another?

I have the following strings in bash

str1="any string"
str2="any"

I want to check if str2 is a substring of str1

I can do it in this way:

c=`echo $str1 | grep $str2`
if [ $c != "" ]; then
    ...
fi

Is there a more efficient way of doing this?

Upvotes: 0

Views: 1061

Answers (4)

P.P
P.P

Reputation: 121407

You can use wild-card expansion *.

str1="any string"
str2="any"

if [[ "$str1" == *"$str2"* ]]
then
  echo "str2 found in str1"
fi

Note that * expansion will not work with single [ ].

Upvotes: 4

speakr
speakr

Reputation: 4209

You can use bash regexp matching without using grep:

if [[ $str1 =~ $str2 ]]; then
    ...
fi

Note that you don't need any surrounding slashes or quotes for the regexp pattern. If you want to use glob pattern matching just use == instead of =~ as operator.

Some examples can be found here.

Upvotes: 1

Alex North-Keys
Alex North-Keys

Reputation: 4373

str1="any string"
str2="any"

Old school (Bourne shell style):

case "$str1" in *$str2*)
    echo found it
esac

New school (as speakr shows), however be warned that the string to the right will be viewed as a regular expression:

if [[ $str1 =~ $str2 ]] ; then
    echo found it
fi

But this will work too, even if you're not exactly expecting it:

str2='.*[trs].*'
if [[ $str1 =~ $str2 ]] ; then
    echo found it
fi

Using grep is slow, since it spawns a separate process.

Upvotes: 3

merlin
merlin

Reputation: 69

if echo $str1 | grep -q $str2    #any command 
   then
   .....
fi

Upvotes: 0

Related Questions