【问题标题】:Check if string containts slash or backslash in Bash?检查字符串是否在 Bash 中包含斜杠或反斜杠?
【发布时间】:2013-08-11 12:21:51
【问题描述】:

我目前正在尝试让我的 bash 脚本检查字符串是否包含 "/""\",但不知何故我无法让它工作。

这是我目前得到的:

if [[ "$1" == *\/* ]]; then
   ...
elif if [[ "$1" == *\\* ]]; then
   ...
fi

非常感谢您的帮助!谢谢

【问题讨论】:

    标签: regex string bash backslash


    【解决方案1】:

    这会检查\/ 是否在变量$string 中。

    if [[ "$string" == *\/* ]] || [[ "$string" == *\\* ]]
    then
      echo "yes"
    fi
    

    测试:

    $ string="hello"
    $ if [[ "$string" == *\/* ]] || [[ "$string" == *\\* ]]; then echo "yes"; fi
    $
    $ string="hel\lo"
    $ if [[ "$string" == *\/* ]] || [[ "$string" == *\\* ]]; then echo "yes"; fi
    yes
    $ string="hel//lo"
    $ if [[ "$string" == *\/* ]] || [[ "$string" == *\\* ]]; then echo "yes"; fi
    yes
    

    【讨论】:

    • 如果你使用=~而不是==,则不需要周围的*s。
    • 你也可以写[[ "$string" == *\/* || "$string" == *\\* ]]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 2017-06-20
    相关资源
    最近更新 更多