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?
Asked
Active
Viewed 2.6k times
13
-
1Possible 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 Answers
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
-
-
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
-
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
-
or you could just write `if echo "$input" | grep -q "$pattern"; then`, but that's not really a shell solution. – ams Jul 15 '14 at 09:28
-
-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

user3840020
- 11
- 2
-
1TEST="This is a test"; if [ "$TEST" != ${TEST/his/} ]; then; echo $TEST; fi – user3840020 Jul 15 '14 at 09:02
-
1
-
@user3840020 TEST="This is a test"; if [ "$TEST" != ${TEST/his/} ]; then echo $TEST; f – Jose Velasco Oct 20 '20 at 21:34