MOHAMED
MOHAMED

Reputation: 43558

how to check if a substring exist

I have the following string

msg="bbb. aaa.ccc. bbb.dddd. aaa.eee."

the separator between the sub strings is the space.

I want to check for example if "aaa." exist. in the above msg it does not exist.

I want to check for example if "bbb." exist. in the above msg it exists.

I tried with grep, but grep works with newlines as the separators between substrings

How to do that?

Upvotes: 1

Views: 372

Answers (2)

glenn jackman
glenn jackman

Reputation: 247012

This can be done in bash using pattern matching. You want to check if

  • the substring is at the start of the string
  • the substring is in the middle, or
  • the substring is at the end
# pass the string, the substring, and the word separator
matches() {
    [[ $1 == $2$3* ]] || [[ $1 == *$3$2$3* ]] || [[ $1 == *$3$2 ]]
}
msg="bbb. aaa.ccc. bbb.dddd. aaa.eee."
matches "$msg" "aaa." " " && echo y || echo n
matches "$msg" "bbb." " " && echo y || echo n
n
y

This works with , so it should work with ash too:

str_contains_word() {
    sep=${3:-" "}
    case "$1" in
        "$2$sep"* | *"$sep$2$sep"* | *"$sep$2") return 0;;
        *) return 1;;
    esac
}

msg="bbb. aaa.ccc. bbb.dddd. aaa.eee."
for substr in aaa. bbb.; do
    printf "%s: " "$substr"
    if str_contains_word "$msg" "$substr"; then echo yes; else echo no; fi
done

Upvotes: 2

chepner
chepner

Reputation: 531888

The simplest way is to use the -w option with grep, which would prevent aaa. from matching aaa.ccc.

if fgrep -qw 'aaa.' <<< "$msg"; then
    # Found aaa.
else:
    # Did not find aaa.
fi  

Upvotes: 0

Related Questions