Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux /bin/sh check if string contains X

Tags:

linux

shell

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?

like image 817
user2492861 Avatar asked Jul 15 '14 08:07

user2492861


People also ask

How do you check if a variable contains a string in Linux?

Using Regex Operator Another option to determine whether a specified substring occurs within a string is to use the regex operator =~ . When this operator is used, the right string is considered as a regular expression.

What is $@ in SH?

$@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

How do you check if a string contains a substring in shell script?

To check if a string contains a substring in Bash, use comparison operator == with the substring surrounded by * wildcards.


2 Answers

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.

like image 70
ams Avatar answered Sep 28 '22 19:09

ams


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 [ ]).

like image 23
Fred Foo Avatar answered Sep 28 '22 19:09

Fred Foo