viernes, mayo 14, 2010

Grep multiple lines

http://linux.byexamples.com/archives/304/grep-multiple-lines/

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.