15

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?

1

3 Answers 3

22

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.

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

4 Comments

I tried this but it didn't work #!/bin/sh myvar="HELLO" myothervar="HELLOHELLOHELLO" case "$myvar" in $myothervar) echo yes ;; * ) echo no ;; esac
The stars, *, either side are significant and must be there.
Contrary to my previous comment (now deleted), it does do variable expansion. It's the missing stars that are the problem.
Also, you have myvar and myothervar backwards.
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 [ ]).

2 Comments

or you could just write if echo "$input" | grep -q "$pattern"; then, but that's not really a shell solution.
@ams naming matters :)
-1

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

TEST="This is a test"
if [ "$TEST" != "${TEST/his/}" ]
then
echo "$TEST"
fi

3 Comments

TEST="This is a test"; if [ "$TEST" != ${TEST/his/} ]; then; echo $TEST; fi
I get [: is: unexpected operator/operand
@user3840020 TEST="This is a test"; if [ "$TEST" != ${TEST/his/} ]; then echo $TEST; f

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.