我如何比较一个变量的字符串(并做一些事情,如果他们匹配)?


当前回答

Bash 4+示例。注意:当单词中包含空格时,不使用引号会导致问题。在我看来,总是用Bash引用。

下面是Bash 4+中的一些例子:

例1,在字符串中检查'yes'(不区分大小写):

    if [[ "${str,,}" == *"yes"* ]] ;then

例2,检查字符串中的'yes'(不区分大小写):

    if [[ "$(echo "$str" | tr '[:upper:]' '[:lower:]')" == *"yes"* ]] ;then

例3,检查字符串中的'yes'(区分大小写):

     if [[ "${str}" == *"yes"* ]] ;then

例4,检查字符串中的'yes'(区分大小写):

     if [[ "${str}" =~ "yes" ]] ;then

例5,精确匹配(区分大小写):

     if [[ "${str}" == "yes" ]] ;then

例6,精确匹配(不区分大小写):

     if [[ "${str,,}" == "yes" ]] ;then

例7,精确匹配:

     if [ "$a" = "$b" ] ;then

享受。

其他回答

你也可以使用用例/esac:

case "$string" in
 "$pattern" ) echo "found";;
esac

下面的脚本逐行读取名为“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

我这样做,是兼容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

你是否存在比较问题?(如下面?)

var="true"
if [[ $var == "true" ]]; then
  # It should be working, but it is not...
else
  # It is falling here...
fi

试试=~操作符(正则表达式操作符),它可能会工作:

var="true"
if [[ $var =~ "true" ]];then
  # Now it works here!!
else
  # No more inequality
fi

Bash正则表达式运算符=~(官方参考) StackOverflow的进一步示例(此处)

Bash 4+示例。注意:当单词中包含空格时,不使用引号会导致问题。在我看来,总是用Bash引用。

下面是Bash 4+中的一些例子:

例1,在字符串中检查'yes'(不区分大小写):

    if [[ "${str,,}" == *"yes"* ]] ;then

例2,检查字符串中的'yes'(不区分大小写):

    if [[ "$(echo "$str" | tr '[:upper:]' '[:lower:]')" == *"yes"* ]] ;then

例3,检查字符串中的'yes'(区分大小写):

     if [[ "${str}" == *"yes"* ]] ;then

例4,检查字符串中的'yes'(区分大小写):

     if [[ "${str}" =~ "yes" ]] ;then

例5,精确匹配(区分大小写):

     if [[ "${str}" == "yes" ]] ;then

例6,精确匹配(不区分大小写):

     if [[ "${str,,}" == "yes" ]] ;then

例7,精确匹配:

     if [ "$a" = "$b" ] ;then

享受。