shell 如何在Bash中检查字符串是否包含子串列表

c9x0cxw0  于 2023-03-19  发布在  Shell
关注(0)|答案(2)|浏览(174)

例如:

#!/bin/bash

STR='foobar/group/dog/name'
SUB=["group/dog/name", "group/dog2/name"]

if [[ "$STR" contains *"$SUB"* ]]; then
  echo "It's there and print out the matching substring: group/dog/name"
fi

类似上面的东西,我还是个新手,有人能帮忙吗?谢谢。

dgsult0t

dgsult0t1#

这也许就是你想做的

#!/bin/bash

str='foobar/group/dog/name'
subs=('group/dog/name' 'group/dog2/name')

for sub in "${subs[@]}"; do
    if [[ $str = *"$sub"* ]]; then
        echo "$sub"
    fi
done
hwazgwia

hwazgwia2#

使用针阵列构建正则表达式并使用grep

subs=('group/dog/name' 'group/dog2/name')
if echo 'foobar/group/dog/name' | grep -qE "$(IFS='|'; echo "${subs[*]}")"; then
  echo "FOUND"
fi

如果堆栈是数组,则可以将其连接以进行测试

srcstr=('some/group/dog/name' 'group/dog3/name')
subs=('group/dog/name' 'group/dog2/name')
if printf '%s' "${srcstr[@]}" | grep -qE "$(IFS='|'; echo "${subs[*]}")"; then
    echo "FOUND"
fi

相关问题