mike628
mike628

Reputation: 49351

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

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?

Upvotes: 40

Views: 60522

Answers (4)

harleygolfguy
harleygolfguy

Reputation: 805

This way is easier for me:

grep --no-group-separator -B5 "pattern" file | sed -n 1~5p

This greps 5 lines before and including the pattern, turns off the --- group separator, then prints every 5th line.

Upvotes: 6

Chris Eberle
Chris Eberle

Reputation: 48785

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.

Upvotes: 37

bmk
bmk

Reputation: 14147

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.

Upvotes: 9

CharlesB
CharlesB

Reputation: 90336

This is option -B

   -B NUM, --before-context=NUM
    Print  NUM  lines  of  leading  context  before  matching lines.
    Places  a  line  containing  --  between  contiguous  groups  of
    matches.

Upvotes: 7

Related Questions