我如何比较一个变量的字符串(并做一些事情,如果他们匹配)?
当前回答
要比较字符串和通配符,使用:
if [[ "$stringA" == *"$stringB"* ]]; then
# Do something here
else
# Do something here
fi
其他回答
我这样做,是兼容Bash和Dash (sh):
testOutput="my test"
pattern="my"
case $testOutput in (*"$pattern"*)
echo "if there is a match"
exit 1
;;
(*)
! echo there is no coincidence!
;;esac
你也可以使用用例/esac:
case "$string" in
"$pattern" ) echo "found";;
esac
如果输入只有几个有效项,我可能会使用regexp匹配。例如,只有“开始”和“停止”是有效的操作。
if [[ "${ACTION,,}" =~ ^(start|stop)$ ]]; then
echo "valid action"
fi
注意,我使用双逗号小写变量$ACTION。还要注意,这在太老的bash版本上不起作用。
下面的脚本逐行读取名为“testonthis”的文件,然后将每行与简单字符串、带有特殊字符的字符串和正则表达式进行比较。如果不匹配,脚本将打印该行,否则不打印该行。
在Bash中,空间非常重要。所以下面的方法是可行的:
[ "$LINE" != "table_name" ]
但下面的情况不会:
["$LINE" != "table_name"]
所以请用as is:
cat testonthis | while read LINE
do
if [ "$LINE" != "table_name" ] && [ "$LINE" != "--------------------------------" ] && [[ "$LINE" =~ [^[:space:]] ]] && [[ "$LINE" != SQL* ]]; then
echo $LINE
fi
done
或者,如果你不需要else子句:
[ "$x" == "valid" ] && echo "x has the value 'valid'"