1

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?

  • I'm not sure if this is the cause of the problem but you should not put a whitespace before and after the `=` character when assigning `string1`. – tshiono Aug 17 '22 at 07:16

2 Answers2

1
#!/bin/bash

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

if [[ $string1 == *"$string2"* ]]; then
    echo "$string2 found"
else
    echo "$string2 not found"
fi
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
1

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
Léa Gris
  • 17,497
  • 4
  • 32
  • 41