Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get specific lines from a text file

I am working on a UNIX box, and trying to run an application, which gives some debug logs to the standard output. I have redirected this output to a log file, but now wish to get the lines where the error is being shown.

My problem here is that a simple

cat output.log | grep FAIL

does not help out. As this shows only the lines which have FAIL in them. I want some more information along with this. Like the 2-3 lines above this line with FAIL. Is there any way to do this via a simple shell command? I would like to have a single command line (can have pipes) to do the above.

like image 619
gagneet Avatar asked Dec 20 '08 19:12

gagneet


People also ask

How do I read a specific line from a file?

Use readlines() to Read the range of line from the File You can use an index number as a line number to extract a set of lines from it. This is the most straightforward way to read a specific line from a file in Python. We read the entire file using this way and then pick specific lines from it as per our requirement.

How do I extract a specific line from a file in Python?

Method 1: fileobject.readlines() A file object can be created in Python and then readlines() method can be invoked on this object to read lines into a stream. This method is preferred when a single line or a range of lines from a file needs to be accessed simultaneously.


2 Answers

grep -C 3 FAIL output.log

Note that this also gets rid of the useless use of cat (UUOC).

like image 197
PEZ Avatar answered Nov 13 '22 02:11

PEZ


grep -A $NUM

This will print $NUM lines of trailing context after matches.

-B $NUM prints leading context.

man grep is your best friend.

So in your case:

cat log | grep -A 3 -B 3 FAIL

like image 31
Mike Reedell Avatar answered Nov 13 '22 02:11

Mike Reedell