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
andtail
to achieve this:The
-m "$n"
option to grep specifies to stop after then
th match, and-A "$k"
tells grep to outputk
lines from after each match. We then pipe this totail -b "$k"
to output only thosek
lines.