1

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?

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

I don't know if ash does pattern matching the same way within double brackets.
0

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  

4 Comments

You need to escape the dot.
Oops, I think I intended to use fgrep and forgot.
my ash does not support fgrep
How about grep -F? (fgrep is typically just a synonym for that option, so you may not have it either). Note that grep is a separate program, so the options it supports are independent of which shell you are using (but very dependent on what version of grep is installed on your system).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.