search for a variable in a string in bash

Viewed 51

I have a string given below:

string1 = "Hello there, my name is Jack.
Hello there, my name is Jack.
Hello there, my name is Jack."

I'm taking the following input from the string:

read string2

I want to check whether the string2(which is a variable) is present in string1.

I tried running the below command:

output=$(echo $string1 | grep -o "$string2")
echo $output

eg: Let string2="name" The output is empty when I'm running this command. Can someone tell me where am I going wrong?

2 Answers
#!/bin/bash

string1="Hello there, my name is Jack"
string2="name"

if [[ $string1 == *"$string2"* ]]; then
    echo "$string2 found"
else
    echo "$string2 not found"
fi

Alternate method with POSIX-shell grammar:

string1='Hello there, my name is Jack'
string2='name'

case "$string1" in
  *"$string2"*) printf '%s found\n' "$string2";;
  *) printf '%s not found\n' "$string2";;
esac
Related