如何判断一个字符串是否包含Unix shell脚本中的另一个字符串?
发布时间:2022-10-26 15:00:24 所属栏目:Unix 来源:未知
导读: 我想写一个Unix shell脚本,如果在另一个字符串内部有一个字符串,它会做各种逻辑。例如,如果我在某个文件夹,分支。有人可以告诉我如何完成这个吗?如果可能,我想让这不是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
这里是另一个解决方案。这使用 ,所以它工作在bash,dashunix脚本,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"
总结 以上是编程之家为你收集整理的如何判断一个字符串是否包含Unix shell脚本中的另一个字符串?全部内容,希望文章能够帮你解决如何判断一个字符串是否包含Unix shell脚本中的另一个字符串?所遇到的程序开发问题。 如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。 (编辑:天瑞地安资讯网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
