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

后端 未结 4 993
广开言路
广开言路 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:27

    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.

    0 讨论(0)
  • 2020-12-30 20:28

    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.
    
    0 讨论(0)
  • 2020-12-30 20:42

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题