Linux 拨号vps windows公众号手机端

怎么使用shell正则表达式匹配字符串

lewis 9年前 (2017-01-22) 阅读数 9 #程序编程
文章标签 shell

要使用shell正则表达式来匹配字符串,可以使用以下方法:

  1. 使用grep命令:

    echo "hello world" | grep "hello"
    

    输出:

    hello world
    
  2. 使用expr命令:

    string="hello world"
    expr "$string" : 'hello'
    

    输出:

    hello
    
  3. 使用[[ ]]表达式:

    string="hello world"
    if [[ $string =~ "hello" ]]; then
        echo "匹配成功"
    fi
    

    输出:

    匹配成功
    
  4. 使用case语句:

    string="hello world"
    case "$string" in
        *hello*) echo "匹配成功";;
    esac
    

    输出:

    匹配成功
    

这些方法都可以用来匹配字符串,具体使用哪种方法取决于你的需求和上下文。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门