Pau*_*ce. 31
你可以在bash中使用正则表达式:
string="a b '' c '' d"
if [[ "$string" =~ \ |\' ]] # slightly more readable: if [[ "$string" =~ ( |\') ]]
then
echo "Matches"
else
echo "No matches"
fi
Run Code Online (Sandbox Code Playgroud)
编辑:
由于上面显而易见的原因,最好将正则表达式放在变量中:
pattern=" |'"
if [[ $string =~ $pattern ]]
Run Code Online (Sandbox Code Playgroud)
并且在双方括号内不需要引号.它们不能在右侧使用,或者正则表达式更改为文字字符串.
Ste*_* B. 26
case "$var" in
*\ * )
echo "match"
;;
*)
echo "no match"
;;
esac
Run Code Online (Sandbox Code Playgroud)
[[ "$str" = "${str%[[:space:]]*}" ]] && echo "no spaces" || echo "has spaces"
Run Code Online (Sandbox Code Playgroud)
你可以这样做,而不需要任何反斜杠或外部命令:
# string matching
if [[ $string = *" "* ]]; then
echo "string contains one more spaces"
else
echo "string doesn't contain spaces"
fi
# regex matching
re="[[:space:]]+"
if [[ $string =~ $re ]]; then
echo "string contains one or more spaces"
else
echo "string doesn't contain spaces"
fi
Run Code Online (Sandbox Code Playgroud)
有关:
小智 8
string="a b '' c '' d"
if [ "$string" == "${string//[\' ]/}" ]
then
echo did not contain space or single quote
else
echo did contain space or single quote
fi
Run Code Online (Sandbox Code Playgroud)