gpt4 book ai didi

regex - 如何测试字符串是否与 POSIX shell 中的正则表达式匹配? (不是 bash )

转载 作者:行者123 更新时间:2023-12-03 01:13:59 25 4
gpt4 key购买 nike

我使用的是Ubuntu系统shell,而不是bash,我发现常规方式无法工作:

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

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

错误[[:未找到!

我该如何解决这个问题?

最佳答案

[[ ... ]] 是一种 bash-ism。您只需将 grep 与普通 if 结合使用,即可使测试与 shell 无关:

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

关于regex - 如何测试字符串是否与 POSIX shell 中的正则表达式匹配? (不是 bash ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21115121/

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