在Pyhton里判断字符串是否存在包含关系非常简单,只要if a in b就行了,但如何在Shell中判断字符串的包含关系呢?
#! /bin/bash
var1="hello"
var2="he"
#方法1
if [ ${var1:0:2} = $var2 ]; then
echo "1:include"
fi
#方法2
echo "$var1" | grep -q "$var2"
if [ $? -eq 0 ]; then
echo "2:include"
fi
#方法3
echo "$var1" |grep -q "$var2" && echo "include" ||echo "not"
#方法4
[[ "${var1/$var2/}" != "$var2" ]] && echo "include" || echo "not"
其他方法:
expr或awk的index函数
${var#...}
${var%...}
${var/.../...}