加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-15 16:38:38 所属栏目:安全 来源:网络整理
导读:我想写一个Unix shell脚本,如果在另一个字符串内部有一个字符串,它会做各种逻辑。例如,如果我在某个文件夹,分支。有人可以告诉我如何完成这个吗?如果可能,我想让这不是shell具体(即不是bash只)但如果没有其他方式,我可以做到这一点。 #!/usr/bin/env
我想写一个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 parameter expansion,所以它工作在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"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读