Print several lines after nth occurence in bash

awkgrepperltext processing

I'm looking for a way to search for the nth occurrence of a pattern and print k lines after the pattern. I guess awk would work better than grep in this case but I cannot figure out the way to do it properly …

Say I have the following text file:

Draft  
blablablabla  
tralalalalala  
Draft  
blablablabla  
tralalalalala  
Draft  
important line 1  
important line 2  
Draft   
blablablabla   
tralalalalala  

In this case n=3 and k=2, I want to print the 2 lines following the 3th occurrence of the pattern "Draft". In my specific case, n and k may vary.

Is it a simple way to do this ?

Best Answer

You can use grep and tail to achieve this:

$ n=3
$ k=2
$ grep -m "$n" -A "$k" 'Draft' input.txt | tail -n "$k"
important line 1  
important line 2  
$ 

The -m "$n" option to grep specifies to stop after the nth match, and -A "$k" tells grep to output k lines from after each match. We then pipe this to tail -b "$k" to output only those k lines.

Related Question