Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash substring regex matching wildcard

Tags:

regex

bash

I am doing bash , i try to test if the substring "world" in the given variable x. I have part of code working. But the other one not working. I want to figure out why

First one is working

x=helloworldfirsttime
world=world
if [[ "$x"  == *$world* ]];then
    echo matching helloworld

Second one is not working

x=helloworldfirsttime
if [[ "$x"  == "*world*" ]];then
    echo matching helloworld

How to make second one work without using variable like the 1st method

Can someone fix the second one for me.. thanks

like image 470
runcode Avatar asked Nov 01 '25 01:11

runcode


2 Answers

Just remove the quotes:

x=helloworldfirsttime
if [[ "$x" == *world* ]]; then
    echo matching helloworld
fi

Note that this isn't regex (a regex for this would look something like .*world.*). The pattern matching in bash is described here:
http://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html

like image 109
Andrew Clark Avatar answered Nov 02 '25 16:11

Andrew Clark


x=helloworldfirsttime
$ if [[ "$x" == *world* ]]; then echo MATCHING; fi
MATCHING

This works because bash's builtin [[ operator treats the right-hand-side of an == test as a pattern:

When the == and != operators are used, the string to the right of the operator is used as a pattern and pattern matching is performed.

like image 26
PhilR Avatar answered Nov 02 '25 15:11

PhilR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!