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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With