LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   grep line above and below (https://www.linuxquestions.org/questions/programming-9/grep-line-above-and-below-737112/)

poiuytrez 07-02-2009 12:22 AM

grep line above and below
 
Hi,

I have to parse a very large file and I want to use the command grep (or any other tool).

I have to check in a log line the word "FAILED", print the line above and below.

For example:
---------
id : 15
Satus : SUCESS
Message : no problem
---------
id : 15
Satus : FAILED
Message : connection error
---------


And I need to print only
id : 15
Satus : FAILED
Message : connection error


Thank you for your help !

mario.almeida 07-02-2009 12:34 AM

Use grep -A1 -B1 ^id file_name


Quote:

Originally Posted by poiuytrez (Post 3593806)
Hi,

I have to parse a very large file and I want to use the command grep (or any other tool).

I have to check in a log line the word "FAILED", print the line above and below.

For example:
---------
id : 15
Satus : SUCESS
Message : no problem
---------
id : 15
Satus : FAILED
Message : connection error
---------


And I need to print only
id : 15
Satus : FAILED
Message : connection error


Thank you for your help !


sycamorex 07-02-2009 12:45 AM

Code:

grep -C 1 FAILED name_of_the_file
or

Code:

grep -1 FAILED name_of_the_file

ghostdog74 07-02-2009 01:29 AM

See here (example 8) using awk

poiuytrez 07-02-2009 02:03 AM

Thanks sycamorex !

It really works good !

archtoad6 07-04-2009 04:18 PM

I know it's considered rude to tell you to RT:)M, the options suggested are in the 1st 6 in the man page:
Quote:

-A NUM, - -after-context=NUM
Print NUM lines of trailing context after matching lines. Places a line containing - - between contiguous groups of matches.
-a, - -text
...
-B NUM, - -before-context=NUM
Print NUM lines of leading context before matching lines. Places a line containing - - between contiguous groups of matches.
-b, - -byte-offset
...
- -binary-files=TYPE
...
-C NUM, - -context=NUM
Print NUM lines of output context. Places a line containing - - between contiguous groups of matches.
Did you even bother to look?

BTW, grep is one of those man pages that should be re-read regularly.

ghostdog74 07-04-2009 08:27 PM

Quote:

Originally Posted by archtoad6 (Post 3596828)
I know it's considered rude to tell you to RTFM, the options suggested are in the 1st 6 in the man page:

no, its not rude at all. Its just common sense to look there first, after that, google next if still in doubt. Further more, if the answer is exactly written in man page, its alright to tell him to RTFM


All times are GMT -5. The time now is 04:07 PM.