如何测试字符串是否与POSIX shell中的模式匹配? (不是bash)

问题描述 投票:18回答:4

我正在使用Ubuntu系统外壳,而不是bash,但是我发现常规方法无法正常工作:

#!/bin/sh
string='My string';

if [[ $string =~ .*My.* ]]
then
   echo "It's there!"
fi

错误[[:找不到!

如何解决此问题?

regex shell sh posix
4个回答
18
投票

[[ ... ]]是一种bash-ism。您可以通过仅将grep与常规if结合使用来使您的测试与外壳程序无关:

if echo "$string" | grep -q "My"; then
    echo "It's there!"
fi

20
投票

为什么将grep


5
投票

您可以使用expr


0
投票
[ "${string#*My}" != "$string" ] && echo "It's there!"

${...}
© www.soinside.com 2019 - 2024. All rights reserved.