13

In a shell script, how can I find out if a string is contained within another string. In bash, I would just use =~, but I am not sure how I can do the same in /bin/sh. Is it possible?

user2492861
  • 385
  • 2
  • 5
  • 13
  • 1
    Possible duplicate of [How do you tell if a string contains another string in Unix shell scripting?](http://stackoverflow.com/questions/2829613/how-do-you-tell-if-a-string-contains-another-string-in-unix-shell-scripting) – Daniele Orlando Mar 12 '16 at 00:21

3 Answers3

18

You can use a case statement:

case "$myvar" in
*string*) echo yes ;;
*       ) echo no ;;
esac

All you have to do is substitute string for whatever you need.

For example:

case "HELLOHELLOHELLO" in
*HELLO* ) echo "Greetings!" ;;
esac

Or, to put it another way:

string="HELLOHELLOHELLO"
word="HELLO"
case "$string" in
*$word*) echo "Match!" ;;
*      ) echo "No match" ;;
esac

Of course, you must be aware that $word should not contain magic glob characters unless you intend glob matching.

ams
  • 24,923
  • 4
  • 54
  • 75
  • I tried this but it didn't work #!/bin/sh myvar="HELLO" myothervar="HELLOHELLOHELLO" case "$myvar" in *$myothervar*) echo yes ;; * ) echo no ;; esac – user2492861 Jul 15 '14 at 09:06
  • The stars, `*`, either side are significant and *must* be there. – ams Jul 15 '14 at 09:14
  • Contrary to my previous comment (now deleted), it *does* do variable expansion. It's the missing stars that are the problem. – ams Jul 15 '14 at 09:18
  • Also, you have `myvar` and `myothervar` backwards. – ams Jul 15 '14 at 09:21
1

You can define a function

matches() {
    input="$1"
    pattern="$2"
    echo "$input" | grep -q "$pattern"
}

to get regular expression matching. Note: usage is

if matches input pattern; then

(without the [ ]).

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
-1

You can try lookup 'his' in 'This is a test'

TEST="This is a test"
if [ "$TEST" != "${TEST/his/}" ]
then
echo "$TEST"
fi
Deleted User
  • 2,551
  • 1
  • 11
  • 18