Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I'd like to do a plain substring match with shell scripts

Tags:

shell

I'd like know how to do a plain substring match in a shell script.

For example, if I have

STRING1="http://127.0.0.1/"
STRING2="http://127101011/"
SUBSTRING="127.0.0.1"

I want SUBSTRING to match STRING1 but not STRING2. It's like java.lang.String.indexOf(String).

I guess the problem can also be fixed by properly escaping the content of SUBSTRING, too, but I can't seem to figure out how to.

like image 456
wbkang Avatar asked Mar 19 '26 09:03

wbkang


1 Answers

STRING1="http://127.0.0.1/"
STRING2="http://127101011/"
SUBSTRING="127.0.0.1"
for string in "$STRING1" "$STRING2"
do
    case "$string" in
    (*$SUBSTRING*) echo "$string matches";;
    (*)            echo "$string does not match";;
    esac
done

The '(*)' notation in the case works in Korn shell and Bash; it won't work in the original Bourne shell - that requires no leading '('.

Alternatively, the expr command can be used - that is another classic (and POSIX) command that is probably made obsolete by some of the features in more modern shells.

like image 139
Jonathan Leffler Avatar answered Mar 21 '26 04:03

Jonathan Leffler



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!