在没有perl支持的情况下,是否可以在grep中执行后视和前瞻性断言? [英] Is it possible to perform look behind and look ahead assertions in grep without perl support?

查看:144
本文介绍了在没有perl支持的情况下,是否可以在grep中执行后视和前瞻性断言?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许像vi?

我的perl等效项是:

My perl equivalent is:

grep -Po '(?<=^.L.........\s).*(?=\s->\s)' rsync_itemized.log

找到所有符号链接修改并输出文件名部分.显然,我可以使用awk:

Which finds all the symlink modifications and outputs the filename part. Obviously, I can use awk:

awk '$1 ~ /^.L........./ { print $2 }' rsync_itemized.log

但是我想知道grep原生正则表达式引擎是否支持它.

But I was wondering if greps native regex engine supports it.

推荐答案

一些注意事项:

  • grep -P使用 libpcre ,这是一个Perl- 兼容
  • 如果文件名中有空格,您的awk命令将不起作用
  • grep -P uses libpcre, a compiled library (written in C, not perl) that is perl-compatible
  • Your awk command won't work if there is a space in the file name

sed命令会更好一些:

sed '/^.L......... /!d; s///; / -> .*/!d; s///'

这将删除所有与第一个正则表达式不匹配的行,然后删除其余行的匹配部分,然后对第二个正则表达式进行相同的操作,将文本留在中间.由于正则表达式为贪婪,因此第二个正则表达式会将a -> b -> c转换为a即使您想要a -> b,所以这也不是完美的解决方案.

This deletes all lines that do not match the first regex, then removes the matching portion of the remaining lines, then does the same for the second regex, leaving you with the text in the middle. Since regexps are greedy, the second regex will turn a -> b -> c into a even though you wanted a -> b, so this isn't a perfect solution either.

也许您可以直接使用perl(我假设您使用的是没有libpcre库的grep编译系统,因此无法执行-P,但是也许您仍然可以访问perl ):

Perhaps you can use perl directly (I assume you're on a system for which grep was compiled without the libpcre library and therefore can't do -P but perhaps you still have access to perl):

perl -ne '/^.L.........\s(.*)\s->\s/ and print "$1\n"'

这次,贪婪对我们有利(正则表达式从左到右进行评估),您将正确提取名为a -> b的文件,该文件与c链接.

This time, greediness works in our favor (regexps are evaluated left to right) and you'll correctly extract a file named a -> b that is symlinked to c.

如果您具有 GNU sed (几乎是任何Linux系统),则可以模仿这种逻辑:

If you have GNU sed (nearly any Linux system), you can mimic that logic:

sed '/^.L.........\s\(.*\)\s->\s.*/!d; s//\1/'

 

但是从技术上讲,我还没有回答您的问题,这是关于在没有-P的情况下使用grep的问题. grep使用基本和扩展的POSIX正则表达式(BRE和ERE).甚至ERE也无法满足您的需求,因此快速的答案是,如果没有-P,则无法在单个grep命令中执行此操作.您可能可以使用多个grep命令来执行此操作,但这非常丑陋,我要说的是,如果没有环视或文本替换,您实际上是无法做到的,而BRE或ERE都不提供.

But I haven't technically answered your question, which was about using grep without -P. grep uses basic and extended POSIX regular expressions (BRE and ERE). Even ERE can't do what you're looking for, so the quick answer is that you cannot do this in a single grep command without -P. You might be able to do it with multiple grep commands, but it would be extremely ugly and I'm leaning on saying you actually cannot do it without look-arounds or text replacement, neither of which are available in BRE or ERE.

这篇关于在没有perl支持的情况下,是否可以在grep中执行后视和前瞻性断言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆