如何检查字符串是否在Bash shell中有空格

der*_*dji 29 string bash shell

说一个字符串可能就像"ab''c''d".如何检查字符串中是否包含单/双引号和空格?

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)

  • 我在挑剔,但你不需要引用$ var. (3认同)
  • 感谢您引用它并为一般的脚本设置一个很好的例子,即使在这个特定实例中它不是绝对必要的。 (2认同)

gle*_*man 9

[[ "$str" = "${str%[[:space:]]*}" ]] && echo "no spaces" || echo "has spaces"
Run Code Online (Sandbox Code Playgroud)

  • 请注意,对于那些好奇的人来说,这不会检测制表符或换行符 (3认同)

cod*_*ter 9

你可以这样做,而不需要任何反斜杠或外部命令:

# 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)

有关:

  • 最好的最新答案,因为它通过提供两个可移植且在代码审查期间非常容易理解的选项来专门回答问题 - 字符串中的空格。请像@codeforester 这样的人保持简单;最好的软件永远是。 (2认同)
  • 正则表达式版本更为通用,因为它也可以找到\ t和\ n和\ r。[:space:]“空格字符,例如空格,换页符,换行符,回车符,水平制表符和垂直制表符” https://www.oreilly.com/library/view/oracle-regular-expressions/0596006012/ re08.html (2认同)

小智 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)