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

后端 未结 4 1011
广开言路
广开言路 2020-12-30 19:57

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 b

4条回答
  •  天命终不由人
    2020-12-30 20:46

    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.

提交回复
热议问题