【问题标题】:grep: repetition-operator operand invalidgrep:重复运算符操作数无效
【发布时间】:2013-03-10 10:15:13
【问题描述】:

我有这个普通快递(?<=heads\/)(.*?)(?=\n),你可以在这里看到它的工作原理 http://regexr.com?347dm

我需要这个正则表达式才能在 grep 命令中工作,但我收到了这个错误。

$ grep -Eio '(?<=heads\/)(.*?)(?=\n)' text.txt 
grep: repetition-operator operand invalid

它在 ack 中效果很好,但我在需要运行它的机器上没有 ack。

ack text.txt -o --match '(?<=heads\/)(.*?)(?=\n)'

文本.txt

74f3649af36984e1b784e46502fe318e91d29570    HEAD
06d4463ab47a6246e6bd94dc3b9267d59fc16c2e    refs/heads/ARC
0597e13c22b6397a1b260951f9d064f668b26f08    refs/heads/LocationAge
e7e1ed942d15efb387c878b9d0335b37560c8807    refs/heads/feature/311-312-breaking-banner-updates
d0b2632b465702d840a358d0b192198ae505011c    refs/heads/gulf-news
509173eafc6792739787787de0d23b0c804d4593    refs/heads/jbb-new-applicationdidfinishlaunching
1e7b03ce75b1a7ba47ff4fb5128bc0bf43a7393b    refs/heads/locationdebug
74f3649af36984e1b784e46502fe318e91d29570    refs/heads/master
5d2ede384325877c24db7ba1ba0338dc7b7f84fb    refs/heads/mixed-media
3f3b6a81dd3baea8744aec6b95c2fe4aaeb20ea3    refs/heads/post-onezero
4198a43aab2dfe72d7ae9e9e53fbb401fc9dac1f    refs/heads/whitelabel
76741013b3b2200de29f53800d51dfd6dc7bac5e    refs/tags/r10
fc53b1a05dad3072614fb397a228819a67615b82    refs/tags/r10^{}
afdcfd970c9387f6fda0390ef781c2776aa666c3    refs/tags/r11

【问题讨论】:

  • 在您的系统上 grep 和 ack 似乎接受略有不同的正则表达式语法。从正则表达式中删除重复字符,直到找到 grep 不喜欢的字符。
  • 我的错误。我编辑它是正确的。同样的问题。
  • 你误解了我的评论。我是说 grep 正则表达式语言和 ack 正则表达式语言不一样。我正在尝试帮助您自己调试问题以找出差异。 (Here's the answer.)
  • jspooner:我是ack的作者,问题是ack使用了Perl正则表达式,因为它是一个Perl应用。 grep 不使用 Perl 正则表达式,因此存在差异,正如您所发现的。至于“我在这台机器上没有 ack”,ack 是一个文件,你可以在 beyondgrep.com/install 使用单个命令行下载,不需要 root 权限。

标签: grep ack


【解决方案1】:

grep 不支持 (?&lt;=...)*?(?=...) 运算符。见this table

【讨论】:

  • 我用过*,感谢您的解决方案,与我合作得很好
【解决方案2】:
$ grep -Pio '(?<=heads\/)(.*?)(?=\n)' text.txt # P option instead of E

如果您使用 GNU grep,则可以使用 -P--perl-regexp 选项。

如果您使用的是 OS X,则需要安装 GNU grep。

$ brew install grep 

由于最近的changes,要在 macOS 上使用 GNU grep,您必须在命令前加上“g”

$ ggrep -Pio '(?<=heads\/)(.*?)(?=\n)' text.txt # P option instead of E

或者改成path name

【讨论】:

  • 如果grep现在不支持-P怎么办?
  • @Irina 你是什么意思?它应该仍然支持-P
【解决方案3】:

试试这个

grep -Eoh 'heads/.*' text.txt | grep -Eoh '/.*' | grep -Eoh '[a-zA-Z].*'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-09
    • 2021-03-18
    • 1970-01-01
    • 2015-08-06
    • 2015-01-17
    • 2014-07-27
    • 2019-07-21
    • 2016-09-09
    相关资源
    最近更新 更多