Regex 在bash中使用ggrep-P进行lookback

Regex 在bash中使用ggrep-P进行lookback,regex,bash,grep,gnu,lookbehind,Regex,Bash,Grep,Gnu,Lookbehind,我正在编写一个bash脚本,我想在ggrep中使用lookbehind来查找字符串中的特定值 在构建概念验证示例时,我可以在使用grep时返回一个结果,但它为我提供了整行内容,而不是我指定的lookback之前的内容: $echo "this and that 12 those" | ggrep -P '(?<=this\sand\sthat)[\s\d]+' this and that 12 those 您必须添加-o选项 -o, --only-matching

我正在编写一个bash脚本,我想在ggrep中使用lookbehind来查找字符串中的特定值

在构建概念验证示例时,我可以在使用grep时返回一个结果,但它为我提供了整行内容,而不是我指定的lookback之前的内容:

$echo "this and that 12 those" | ggrep -P '(?<=this\sand\sthat)[\s\d]+'

this and that 12 those 

您必须添加
-o
选项

-o, --only-matching
              Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.
这条线变成这样:


echo“这个和那个12个”| ggrep-o-p'(?如果这像grep一样工作,尝试添加
-o
选项。
echo“这个和那个12个”| ggrep-o-p”(?太好了,这就解决了。你想把这个作为帖子的答案来回复吗,这样我就可以从我的角度来检查它了?@nico,把它作为一个答案发布一个关于lookbehinds的注释:你不能使用可变宽度的lookbehinds,这有时是一个痛苦的问题。但是Perl有一个regex指令
\K
,它完成了同样的事情:它处理所有可能发生的事情在
\K
之前,基本上是作为一个lookback。这是非法的:
grep-oP'(?@glennjackman,感谢您的注释re:variable widths in lookbacks in using perl。我在不久前发布的另一个堆栈溢出问题中了解到了这一点,在这里为未来的搜索者指出这是一个非常好的事实。
-o, --only-matching
              Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.