不要将连续匹配的上下文与grep合并 [英] Do not merge the context of contiguous matches with grep

查看:47
本文介绍了不要将连续匹配的上下文与grep合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在以下文件上运行 grep -C 1匹配:

If I run grep -C 1 match over the following file:

a
b
match1
c
d
e
match2
f
match3
g

我得到以下输出:

b
match1
c
--
e
match2
f
match3
g

如您所见,由于连续匹配"match2"和"match3"周围的上下文重叠,因此将它们合并.但是,我希望为每个匹配项获得一个上下文描述,可能会从上下文报告中的输入中复制行.在这种情况下,我想要的是:

As you can see, since the context around the contiguous matches "match2" and "match3" overlap, they are merged. However, I would prefer to get one context description for each match, possibly duplicating lines from the input in the context reporting. In this case, what I would like is:

b
match1
c
--
e
match2
f
--
f
match3
g

实现此目标的最佳方法是什么?我希望解决方案具有足够的通用性,可以轻松适应其他 grep 选项( -A -B 的不同值-C 或完全不同的标志).理想情况下,我希望仅使用 grep ....

What would be the best way to achieve this? I would prefer solutions which are general enough to be trivially adaptable to other grep options (different values for -A, -B, -C, or entirely different flags). Ideally, I was hoping that there was a clever way to do that just with grep....

推荐答案

我认为使用普通grep不可能做到这一点.

I don't think this is possible using plain grep.

您曾经使用过Python吗?在我看来,这是完成此类任务的理想语言(此代码段适用于Python 2.7和3.x):

Have you ever used Python? In my opinion it's a perfect language for such tasks (this code snippet will work for both Python 2.7 and 3.x):

with open("your_file_name") as f:
   lines = [line.rstrip() for line in f.readlines()]
   for num, line in enumerate(lines):
      if "match" in line:
         if num > 0:
            print(lines[num - 1])

         print(line)

         if num < len(lines) - 1:
            print(lines[num + 1])
            if num < len(lines) - 2:
               print("--")

这给了我

b
match1
c
--
e
match2
f
--
f
match3
g

这篇关于不要将连续匹配的上下文与grep合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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