Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do not merge the context of contiguous matches with grep

Tags:

grep

matching

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

a
b
match1
c
d
e
match2
f
match3
g

I get the following output:

b
match1
c
--
e
match2
f
match3
g

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

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....

like image 887
a3nm Avatar asked May 28 '11 18:05

a3nm


2 Answers

I don't think it is possible to do that using plain grep.

the sed construct below works to some extent, now I only need to figure out how to add the "--" separator

$ sed -n -e '/match/{x;1!p;g;$!N;p;D;}' -e h log
b
match1
c
e
match2
f
f
match3
g
like image 77
Fredrik Pihl Avatar answered Sep 28 '22 00:09

Fredrik Pihl


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

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("--")

This gives me:

b
match1
c
--
e
match2
f
--
f
match3
g
like image 33
pawroman Avatar answered Sep 28 '22 01:09

pawroman