Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make 'grep' show a single line five lines above the grepped line?

Tags:

file

grep

I've seen some examples of grepping lines before and after, but I'd like to ignore the middle lines. So, I'd like the line five lines before, but nothing else. Can this be done?

like image 452
mike628 Avatar asked Jun 08 '11 15:06

mike628


People also ask

How do you get 5 lines before and after grep?

You can use grep with -A n option to print N lines after matching lines. Using -B n option you can print N lines before matching lines. Using -C n option you can print N lines before and after matching lines.

How do you grep a line above it?

To also show you the lines before your matches, you can add -B to your grep. The -B 4 tells grep to also show the 4 lines before the match. Alternatively, to show the log lines that match after the keyword, use the -A parameter. In this example, it will tell grep to also show the 2 lines after the match.

How do I print above and below lines in grep?

It is possible to print a line above or below (or both) a line having a pattern using grep by using -A , -B or -C flags with num value. Here num denotes the number of additional lines to be printed which is just above or below the matched line.

How do you grep 3 lines after a match?

For BSD or GNU grep you can use -B num to set how many lines before the match and -A num for the number of lines after the match. If you want the same number of lines before and after you can use -C num . This will show 3 lines before and 3 lines after.


2 Answers

OK, I think this will do what you're looking for. It will look for a pattern, and extract the 5th line before each match.

grep -B5 "pattern" filename | awk -F '\n' 'ln ~ /^$/ { ln = "matched"; print $1 } $1 ~ /^--$/ { ln = "" }' 

basically how this works is it takes the first line, prints it, and then waits until it sees ^--$ (the match separator used by grep), and starts again.

like image 164
Chris Eberle Avatar answered Sep 19 '22 15:09

Chris Eberle


If you only want to have the 5th line before the match you can do this:

grep -B 5 pattern file | head -1 

Edit:
If you can have more than one match, you could try this (exchange pattern with your actual pattern):

sed -n '/pattern/!{H;x;s/^.*\n\(.*\n.*\n.*\n.*\n.*\)$/\1/;x};/pattern/{x;s/^\([^\n]*\).*$/\1/;p}' file 

I took this from a Sed tutorial, section: Keeping more than one line in the hold buffer, example 2 and adapted it a bit.

like image 41
bmk Avatar answered Sep 19 '22 15:09

bmk