grep last match and it's following lines

后端 未结 2 1816
刺人心
刺人心 2021-02-09 09:58

I\'ve learnt how to grep lines before and after the match and to grep the last match but I haven\'t discovered how to grep the last match

2条回答
  •  眼角桃花
    2021-02-09 10:20

    The approach I would take it to reverse the problem as it's easier to find the first match and print the context lines. Take the file:

    $ cat file
    foo
    1
    2
    foo
    3
    4
    foo
    5
    6
    

    Say we want the last match of foo and the following to lines we could just reverse the file with tac, find the first match and n lines above using -Bn and stop using -m1. Then simple re-reverse the output with tac:

    $ tac file | grep foo -B2 -m1 | tac
    foo
    5
    6
    

    Tools like tac and rev can make problems that seem difficult much easier.

提交回复
热议问题