Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have a large log file I want to review. All the bad stuff starts at the certain occurence of an error string. I want to then look at the last x lines from that point and see what might have caused that error. I can't open the file with my favourite text editor because it exhausts all the RAM on the machine.

I thought perhaps I might be able to find the line it occurs on and then use another utility to get data from x line to y line. Is this possible?

share|improve this question
add comment

1 Answer 1

up vote 4 down vote accepted

You can just use "grep" with the -A and/or -B options. The -A switch will read the X number of lines after the error, so its probably what you want, and the -B switch will read X number of lines before the error, so you would do something like this:

grep -A10 -B2 "string to find" /path/and/file.tofind

To find the 10 lines which occur after "string to find", as well as the 2 lines before it.

Alternatively - and its probably a much worse solution, you could simply use "head" and "tail" to find the first and then the last part of the file you want,but this assumes you know the line numbers. IE if you have a long line file, and you are wanting to read lines 500-510 you might try this:

head -510 /etc/file/to/search | tail -10

Which would first extract the first 510 lines of the file, and then read off the last 10 of those lines.

share|improve this answer
1  
if not using a regexp pattern, grep -F will give best performance. –  suspectus Sep 24 '13 at 19:34
    
This is nice, I didn't know about these switches. By the time you answered, I had achieved this by using grep -n to get the line number, and sed '#,#p' to get a line range. If the error string occurs frequently do these switches only return lines for the first occurrence? Can I use m 1 to achieve that if not? –  deed02392 Sep 24 '13 at 21:06
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.