我如何比较一个变量的字符串(并做一些事情,如果他们匹配)?
当前回答
或者,如果你不需要else子句:
[ "$x" == "valid" ] && echo "x has the value 'valid'"
其他回答
Bash 4+示例。注意:当单词中包含空格时,不使用引号会导致问题。在我看来,总是用Bash引用。
下面是Bash 4+中的一些例子:
例1,在字符串中检查'yes'(不区分大小写):
if [[ "${str,,}" == *"yes"* ]] ;then
例2,检查字符串中的'yes'(不区分大小写):
if [[ "$(echo "$str" | tr '[:upper:]' '[:lower:]')" == *"yes"* ]] ;then
例3,检查字符串中的'yes'(区分大小写):
if [[ "${str}" == *"yes"* ]] ;then
例4,检查字符串中的'yes'(区分大小写):
if [[ "${str}" =~ "yes" ]] ;then
例5,精确匹配(区分大小写):
if [[ "${str}" == "yes" ]] ;then
例6,精确匹配(不区分大小写):
if [[ "${str,,}" == "yes" ]] ;then
例7,精确匹配:
if [ "$a" = "$b" ] ;then
享受。
你也可以使用用例/esac:
case "$string" in
"$pattern" ) echo "found";;
esac
a="abc"
b="def"
# Equality Comparison
if [ "$a" == "$b" ]; then
echo "Strings match"
else
echo "Strings don't match"
fi
# Lexicographic (greater than, less than) comparison.
if [ "$a" \< "$b" ]; then
echo "$a is lexicographically smaller then $b"
elif [ "$a" \> "$b" ]; then
echo "$b is lexicographically smaller than $a"
else
echo "Strings are equal"
fi
注:
if和[和]之间的空格很重要 >和<是重定向操作符,因此对于字符串分别使用\>和\<转义。
或者,如果你不需要else子句:
[ "$x" == "valid" ] && echo "x has the value 'valid'"
要比较字符串和通配符,使用:
if [[ "$stringA" == *"$stringB"* ]]; then
# Do something here
else
# Do something here
fi