3

I can find all non-matched lines of file with grep -v 'my_pattern' some_file. Also i can print few strings before/after/around match with -A, -B or -C options of grep. But i can't combine these two options to exclude lines with pattern and certain amount of lines near matched lines - grep shows entire file as result. For example, i have log with a lot of patterns like this:

25.02.2012 10:41:37 here goes memory state
25MiB free
16MiB allocated
max free block is 4MiB

I'd like to filter them. Of course, i can write custom perl/awk script, but is there more elegant way to do this?

Andrey Starodubtsev
  • 5,139
  • 3
  • 32
  • 46

2 Answers2

1

A grep solution:

grep -C2 pattern file | grep -vFf- file

This uses grep -C2 to get the lines from file that you wish to exclude.

Then grep -vFf- takes those lines from stdin and will report all lines not matching.

Caution: This will eliminate all lines matching the 'context' elsewhere in file. So if the context contains a blank line, you will remove all blank lines.

stevesliva
  • 5,351
  • 1
  • 16
  • 39
1

You can use the vim text editor:

:g/my_pattern/-2,//+2d
kev
  • 155,172
  • 47
  • 273
  • 272
  • 2
    one thing i can't undestand - what's the difference between `:g/my_pattern/-2,//+2d` and `:g/my_pattern/-2,+2d`? It looks like they both do the same thing. – Andrey Starodubtsev Feb 25 '12 at 08:33
  • I don't know what the difference is, but I tried both out on a large file. ``:g/my_pattern/-2,+2d`` worked as expected, but ``:g/my_pattern/-2,//+2d`` removed more lines than expected. – DavidW Aug 26 '21 at 12:26