Linux / bin / sh checks if line X contains

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

+8
linux shell
source share
3 answers

You can use the case statement:

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

All you have to do is replace the string with everything you need.

For example:

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

Or in other words:

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

Of course, you should be aware that $word should not contain the glob magic characters unless you intend to match glob.

+11
source share

You can define a function

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

to get regular expression matching. Note: use

 if matches input pattern; then 

(without [ ] ).

+1
source share

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

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

All Articles