【问题标题】:Print matching regex group in grep在 grep 中打印匹配的正则表达式组
【发布时间】:2016-12-30 08:26:46
【问题描述】:

我有此文本https://bitbucket.com/user/repo.git,我想打印repo,即/.git 之间的内容,不包括分隔符。我有这个:

echo https://bitbucket.com/user/repo.git | grep -E -o '\/(.*?)\.git'

但它打印/repo.git。我怎样才能只打印repo

【问题讨论】:

    标签: regex unix


    【解决方案1】:

    [^/]+(?=\.git$) 模式与-P 选项一起使用:

    echo https://bitbucket.com/user/repo.git | grep -P -o '[^/]+(?=\.git$)'
    

    online demo

    [^/]+(?=\.git$) 模式匹配除 / 之外的 1+ 个字符,这些字符后跟在字符串末尾的 .git

    【讨论】:

      【解决方案2】:

      您可以使用sed 来做到这一点

      echo https://bitbucket.com/user/repo.git | sed -e 's/^.\*\\/\\(.\*\\).git$/\1/g'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-02-24
        • 2023-03-19
        • 2017-02-09
        • 1970-01-01
        • 1970-01-01
        • 2022-10-17
        相关资源
        最近更新 更多