Shell脚本中判断字符串是否被包含在内并且使用grep 精确匹配


str1="abcdefgh"
str2="def"

result=$(echo $str1 | grep "${str2}")

if [[ "$result" != "" ]];then
    echo "包含"
else
    echo "不包含"
fi

如果精确的匹配到def呢

其实答案很简单,用grep –w "def" 或者是grep "\都可以实现

-w, --word-regexp         强制 PATTERN 仅完全匹配字词
str1="abcdefgh"
str2="def"

result=$(echo $str1 | grep -w "${str2}")

if [[ "$result" != "" ]];then
    echo "包含"
else
    echo "不包含"
fi