Reputation: 43558
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
Reputation: 247012
This can be done in bash using pattern matching. You want to check if
# 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 dash, 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
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