在 POSIX sh 中,如何判断一个字符串是否包含另一个字符串? [英] How do you tell if a string contains another string in POSIX sh?

查看:43
本文介绍了在 POSIX sh 中,如何判断一个字符串是否包含另一个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to write a Unix shell script that will do various logic if there is a string inside of another string. For example, if I am in a certain folder, branch off. Could someone please tell me how to accomplish this? If possible I would like to make this not shell specific (i.e. not bash only) but if there's no other way I can make do with that.

#!/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 子字符串参数扩展,所以它适用于 Bash,Dash、KornShell (ksh)、Z shell (zsh) 等

Here's yet another solution. This uses POSIX substring parameter expansion, so it works in Bash, Dash, KornShell (ksh), Z shell (zsh), etc.

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

带有一些示例的功能化版本:

A functionalized version with some examples:

# 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 sh 中,如何判断一个字符串是否包含另一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆