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

后端 未结 4 1009
广开言路
广开言路 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.

提交回复
热议问题