I wonder if the spaces in your string ("ab bc de"), I will call it "S", indicate that you are mentally dividing it into words & assuming that your pattern (P="ab") is being tested for as a word? All the solutions discussed so far will give a positive when S="abbcde" or S="zab bc de". Is this what you intend?
The
bash &
grep solutions can narrow the match by using the regex word boundary symbol "\b" (see the
grep man page):
Code:
[[ "$S" =~ "\b$P\b" ]]
echo "$S" | grep "\b$P\b"
,
but the
case method (brilliant suggestion, BTW) needs a more complicated solution:
Code:
case $S in
"$P "*|*" $P "*|*" $P") return 0 ;;
*) return 1 ;;
esac
(Forgive the double pun -- I couldn't resist) It's a case of considering the corner cases.
It may well be that your actual string is very well structured & you don't need to consider this.
HTH someone.