gpt4 book ai didi

shell - 在 POSIX sh 中如何判断一个字符串是否包含另一个字符串?

转载 作者:行者123 更新时间:2023-12-03 04:33:32 26 4
gpt4 key购买 nike

我想编写一个 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、KornShell (ksh)、Z shell (zsh) 等中运行。它还支持字符串中的特殊字符。

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

带有一些测试的功能化版本:

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

testcontains() {
testnum="$1"
expected="$2"
string="$3"
substring="$4"
contains "$string" "$substring"
result=$?
if [ $result -eq $expected ]; then
echo "test $testnum passed"
else
echo "test $testnum FAILED: string=<$string> substring=<$substring> result=<$result> expected=<$expected>"
fi
}

testcontains 1 1 'abcd' 'e'
testcontains 2 0 'abcd' 'ab'
testcontains 3 0 'abcd' 'bc'
testcontains 4 0 'abcd' 'cd'
testcontains 5 0 'abcd' 'abcd'
testcontains 6 1 '' 'a'
testcontains 7 0 'abcd efgh' 'cd ef'
testcontains 8 0 'abcd efgh' ' '
testcontains 9 1 'abcdefgh' ' '
testcontains 10 0 'abcd [efg] hij' '[efg]'
testcontains 11 1 'abcd [efg] hij' '[effg]'
testcontains 12 0 'abcd *efg* hij' '*efg*'
testcontains 13 0 'abcd *efg* hij' 'd *efg* h'
testcontains 14 1 'abcd *efg* hij' '*effg*'
testcontains 15 1 'abcd *efg* hij' '\effg\'
testcontains 16 0 'a\b' '\'
testcontains 17 0 '\' '\'
testcontains 18 1 '[' '\'
testcontains 19 1 '\' '['
testcontains 20 0 '-n' 'n'
testcontains 21 1 'n' '-n'
testcontains 22 0 '*\`[]' '\`'

关于shell - 在 POSIX sh 中如何判断一个字符串是否包含另一个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2829613/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com