你如何判断一个字符串在Unix shell脚本中是否包含另一个字符串?

我想编写一个Unix shell脚本,如果在另一个字符串中有一个字符串,它将执行各种逻辑。 例如,如果我在某个文件夹中,则关闭。 有人可以告诉我如何做到这一点? 如果可能的话,我想让这不是特定的shell(即不是bash),但是如果没有别的办法,我可以用它做。

#!/usr/bin/env sh

if [ "$PWD" contains "String1" ]
then
    echo "String1 present"
elif [ "$PWD" contains "String2" ]
then
    echo "String2 present"
else
    echo "Else"
fi

这是另一个解决方案。 这使用POSIX substring参数扩展,所以它在bash,dash,ksh中工作...

test "${string#*$word}" != "$string" && echo "$word found in $string"

编辑:这是一个好主意,C.罗斯。 这里有一些功能化的版本和一些例子:

# contains(string, substring)
#
# Returns 0 if the specified string contains the specified substring,
# otherwise returns 1.
contains() {
    string="$1"
    substring="$2"
    if test "${string#*$substring}" != "$string"
    then
        return 0    # $substring is in $string
    else
        return 1    # $substring is not in $string
    fi
}

contains "abcd" "e" || echo "abcd does not contain e"
contains "abcd" "ab" && echo "abcd contains ab"
contains "abcd" "bc" && echo "abcd contains bc"
contains "abcd" "cd" && echo "abcd contains cd"
contains "abcd" "abcd" && echo "abcd contains abcd"
contains "" "" && echo "empty string contains empty string"
contains "a" "" && echo "a contains empty string"
contains "" "a" || echo "empty string does not contain a"
contains "abcd efgh" "cd ef" && echo "abcd efgh contains cd ef"
contains "abcd efgh" " " && echo "abcd efgh contains a space"

纯POSIX外壳:

#!/bin/sh
CURRENT_DIR=`pwd`

case "$CURRENT_DIR" in
  *String1*) echo "String1 present" ;;
  *String2*) echo "String2 present" ;;
  *)         echo "else" ;;
esac

像ksh或bash这样的扩展shell具有奇特的匹配机制,但旧式的case非常强大。


可悲的是,我不知道有什么方法可以做到。 但是,使用bash(从版本3.0.0开始,这可能就是你所拥有的),可以使用=〜运算符,如下所示:

#!/bin/bash
CURRENT_DIR=`pwd`

if [[ "$CURRENT_DIR" =~ "String1" ]]
then
 echo "String1 present"
elif [[ "$CURRENT_DIR" =~ "String2" ]]
then
 echo "String2 present"
else
 echo "Else"
fi

作为一个额外的好处(和/或警告,如果你的字符串中有任何有趣的字符),=〜接受正则表达式作为右操作数,如果你省略引号。

链接地址: http://www.djcxy.com/p/6151.html

上一篇: How do you tell if a string contains another string in Unix shell scripting?

下一篇: Sorting sections issue in NSFetchedResultsController