Live Chat!

grep multiple lines

1 votos Vota!!

August 9th, 2007 mysurface Posted in Text Manipulation, grep | Hits: 41383 |

You can grep multiple lines before or after matching the keywords. Here is a simple tips, that what I discover grep capable of. A is after, B is before.

Let say you have the message.txt shows as below:


Aug  5 02:43:12 zion kernel: [    0.000000] Zone PFN ranges:
Aug  5 02:43:12 zion kernel: [    0.000000]   DMA             0 ->     4096
Aug  5 02:43:12 zion kernel: [    0.000000]   Normal       4096 ->   130730
Aug  5 02:43:12 zion kernel: [    0.000000]   HighMem    130730 ->   130730
Aug  5 02:43:12 zion kernel: [    0.000000] early_node_map[1] active PFN ranges
Aug  5 02:43:12 zion kernel: [    0.000000]     0:        0 ->   130730
Aug  5 02:43:12 zion kernel: [    0.000000] DMI 2.3 present.

You can grep “DMA” with -B 1 and -A2

grep -B1 -A2 "DMA" message.txt

It will return

Aug  5 02:43:12 zion kernel: [    0.000000] Zone PFN ranges:
Aug  5 02:43:12 zion kernel: [    0.000000]   DMA             0 ->     4096
Aug  5 02:43:12 zion kernel: [    0.000000]   Normal       4096 ->   130730
Aug  5 02:43:12 zion kernel: [    0.000000]   HighMem    130730 ->   130730

It is useful to grep logs with multiple lines for one entry.

[中文翻译]

7 Responses to “grep multiple lines”

  1. This is damm cool. Never use this option before. Thanks for your tips.

  2. I use that feature all the time. I think grep & sed are my best friends. :)

  3. Could you please me how to do the same in HP-UX?
    Thank you in advance

  4. Sasikanth Malladi Says:

    To do the same on HP-UX, just install GNU grep on your machine.

  5. Shery Vijayan Says:

    Thanks pal , for the tip.
    That was extremely usefull.
    –Shery

  6. I have a slightly more complicated problem. Let’s assume I have a file like below

    sdfsdghf
    DMA
    DMA
    45346768
    sdfsdgfh
    DMA
    DMA
    DMA
    5236472646
    DMA
    *&*(&*(&

    Now I want to find out how many times DMA appear in consecutive lines. How can I do that? In above case I should get result as 2, 3 & 1

  7. Try using
    uniq -c | grep DMA

Leave a Reply

Security Code: