tags:

views:

612

answers:

2

Hello,

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.

Thank you, wbkang

+3  A: 
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.

Jonathan Leffler
Hahaha brilliant solution. I'll make a little function out of that. Thanks!
wbkang
+1  A: 
#!/bin/bash

function is_matching() {
    if [[ `echo "$1" | grep "$2"` != "" ]]; then return 1; fi
    return 0;
}

is_matching "abcd" "bc"
echo $?
is_matching "abcd" "XX"
echo $?

Running that script:

$ ./test
1
0

If you want to do it without forking grep, read this link -> bash string manipulation

Nicolas Viennot
There's no need to use [[ or backticks here: if echo "$1" | grep "$2"; then..
William Pursell