search in text for string

search in text for string

I assigned text to variable
for example :
cafe tea coca > drinks
and i want to check is $i is in "drink" or not

thanks

What shell are you using (e.g. bash, ksh, csh, zsh)?

Can you confirm if "drink" is a file or a another shell text variable.

my shell is bash

---------- Post updated at 05:34 PM ---------- Previous update was at 05:31 PM ----------

and "drink" is another shell text variable
I assigned via ">"
cafe tea coca > drink

you could use bash replace something like this:

drink="cafe tea coca"
[ "${drink}" = "${drink/tea/}" ] || echo "Drink contains tea"

Above will work for ksh93 or bash, Basically we are saying if $drink equals $(replace "tea" with nothing in drink) is false echo "

or use bash in-built compare

[[ "$drink" =~ "tea" ]] && echo "Drink contains tea"
1 Like
#!/bin/bash

drink="cafe tea cocoa"
echo $drink | grep -q $1

if [[ $? == 0 ]]; then
    echo "Match is Found"
fi
1 Like

#!/bin/bash
i=tea
drinks="cafe tea cocoa"
if [[ $drinks = *$i* ]]; then
echo yup
fi


i=tea
drinks="cafe tea cocoa"
case $drinks in
*$i*) echo yup
esac

  • No external programs died during the making of this code
1 Like

Not the most elegant one but still working...

( grep $i <(echo "$drink") >/dev/null 2>&1 ) && echo 'yup !'
1 Like