【问题标题】:Bash grep doesn't return the first regex matchBash grep 不返回第一个正则表达式匹配
【发布时间】:2020-12-02 08:45:13
【问题描述】:

所以我有这样的 shell 脚本:

echo "stackoverflow.com:1111/?a=b&c=d" | grep -o "^.*[/:\n]"

然后它返回

stackoverflow.com:1111/

它不应该返回符号'/'、':'或'\n'之一之前的第一个前缀吗? 如何让它返回

stackoverflow.com:

使用正则表达式?

【问题讨论】:

  • 试试这个echo "stackoverflow.com:1111/?a=b&c=d" | grep -o "^[^/:\n]*"
  • 至少在 Ubuntu 18.04 中可以使用 @Thefourthbird
  • 正则表达式很贪心!
  • \n 是多余的; grep 无论如何都不会超过换行符。

标签: regex shell grep


【解决方案1】:

您可以使用否定字符类 ^[^/:\n]* 排除字符 / :\n

\n-P 一起用于Perl 兼容的正则表达式:

echo "stackoverflow.com:1111/?a=b&c=d" | grep -oP "^[^/:\n]*"

或者从没有-P的字符串中排除空格

echo "stackoverflow.com:1111/?a=b&c=d" | grep -o "^[^/:[:space:]]*"

Bash demo


如果你也想匹配末尾的:,你可以匹配它^[^/:\n]*:

Bash demo

【讨论】:

    【解决方案2】:

    使用-P(Perl 正则表达式),删除多余的\ngrep 不需要,因为它默认是基于行的),并将贪婪修饰符* 更改为非贪婪修饰符@ 987654325@:

    echo "stackoverflow.com:1111/?a=b&c=d" | grep -oP "^.*?[/:]"
    

    输出:

    stackoverflow.com:
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-09
      • 2010-10-05
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 2011-07-14
      相关资源
      最近更新 更多