0

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?

0

4 Answers 4

4

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 [ ].

Sign up to request clarification or add additional context in comments.

4 Comments

Are the quotes necessary in this case? I thought one of the main advantages of [[]] over [] was making quoting unnecessary...
True. It bites if I miss one when it's necessary but an extra doesn't hurt. It's one of those things I force myself to do it always ;-)
Disclaimer: That wasn't me. ;-)
@DevSolar hehe..I know it's not you :)
3
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.

3 Comments

+1 for the case expression. But that's not old-school, it's the current state-of-the-art since it's as POSIXly portable as it gets. BTW, no need to quote $str1; there's no word splitting done after a case.
I wouldn't assume all existing Unix hosts are current with the POSIX standard. That case expression is compatible with much older systems than the [[ ... =~ ... ]] syntax - decades older. Therefore much more portable.
Then we're in violent agreement. The case way of looking for substrings works with any Bourne shell, so is state-of-the-art and to be unconditionally preferred. Anyone using bashisms like [[ ]] is in need for a portability lesson. :-)
1

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.