有几种方法可以做到这一点。
在 bash >= 3 中,你有你描述的正则表达式匹配,例如
$ foo=foobar
$ if [[ $foo =~ f.ob.r ]]; then echo "ok"; fi
ok
请注意,此语法使用正则表达式模式,因此它使用.
而不是?
匹配单个字符。
如果您想要做的只是测试字符串是否包含子字符串,那么还有更经典的方法可以做到这一点,例如
# ${foo/b?r/} replaces "b?r" with the empty string in $foo
# So we're testing if $foo does not contain "b?r" one time
$ if [[ ${foo/b?r/} = $foo ]]; then echo "ok"; fi
您还可以通过以下方式测试字符串是否以表达式开头或结尾:
# ${foo%b?r} removes "bar" in the end of $foo
# So we're testing if $foo does not end with "b?r"
$ if [[ ${foo%b?r} = $foo ]]; then echo "ok"; fi
# ${foo#b?r} removes "b?r" in the beginning of $foo
# So we're testing if $foo does not begin with "b?r"
$ if [[ ${foo#b?r} = $foo ]]; then echo "ok"; fi
ok
有关这些语法的更多信息,请参阅man bash的参数扩展段落。分别使用or代替and将实现最长匹配而不是简单匹配。##
%%
#
%
处理通配符的另一种非常经典的方法是用例:
case $foo in
*bar)
echo "Foo matches *bar"
;;
bar?)
echo "Foo matches bar?"
;;
*)
echo "Foo didn't match any known rule"
;;
esac