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

编程入门 行业动态 更新时间:2024-10-28 05:13:06
本文介绍了如何测试字符串是否与POSIX Shell中的正则表达式匹配? (不是bash)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我使用的是Ubuntu系统外壳,而不是bash,我发现常规方法不起作用:

I'm using Ubuntu system shell, not bash, and I found the regular way can not work:

#!/bin/sh string='My string'; if [[ $string =~ .*My.* ]] then echo "It's there!" fi

错误[[:找不到!

我该怎么做才能解决这个问题?

What can I do to solve this problem?

推荐答案

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

The [[ ... ]] are a bash-ism. You can make your test shell-agnostic by just using grep with a normal if:

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

更多推荐

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

本文发布于:2023-10-09 02:08:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1474406.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   测试   正则表达式   POSIX   Shell

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!