Operating System - HP-UX
1833346 Members
3128 Online
110051 Solutions
New Discussion

Print lines after search pattern

 
SOLVED
Go to solution
Gyankr
Frequent Advisor

Print lines after search pattern

Hi,

I am searching for a pattern in all the log files
I want to know how to print n lines following the first occurrence of the search pattern in the file.

Regards,
Gyan
4 REPLIES 4
James R. Ferguson
Acclaimed Contributor

Re: Print lines after search pattern

Hi Gyan:

# perl -ne '/pattern/ and $n=3;print if ($n-- >0)' file

Regards!

...JRF...
Hein van den Heuvel
Honored Contributor
Solution

Re: Print lines after search pattern

And similar in awk:

With match line:

awk '/pattern/ { x=5 } x-- > 5'

Without match line:
awk 'x-- > 0; /pattern/ { x=5 }'


That 'x-- > 0' test wether x is greater than 0 and subtracts on from x. If it was true then... nothing: the default action it taken which is to print the current input line.

The part '/pattern/ { x=5 }' looks for a match againt whatever pattern text you provide, and if true sets x to a value, here 5 in the example.

Hein.

Dennis Handly
Acclaimed Contributor

Re: Print lines after search pattern

GNU grep has that option: -A
-A, --after-context=NUM print NUM lines of trailing context
Gyankr
Frequent Advisor

Re: Print lines after search pattern

I dont know perl but the awk method was cool.
Thanks everybody.