How can I make grep ignore first N matches in a file, then print (N+1)th match and all k lines after it and then exit.

  • 1
    Did any of the answers work for you?
    – Dan Cecile
    Aug 23, 2011 at 2:32

3 Answers 3


Just pipe the result to tail(1). For example, if N is 10, use tail +11 to skip the first 10 matches:

grep pattern file | tail +11
  • 1
    I don't think this is what he wants (if i understood his question correctly)
    – user31894
    Aug 21, 2011 at 3:51
  • I don't want it. It would only print last match(es).
    – ravi
    Aug 21, 2011 at 5:12
  • This does do that, and in some cases, faster than awk.
    – bschlueter
    May 25, 2019 at 20:27

An alternative solution in awk:

awk '/pattern/ { found++ } found > N && printed <= K { print; printed++ }' file

More readably:

awk '
# Initialize to zero for clarity
  found = 0
  printed = 0

# Check for a pattern match
/pattern/ {
  # Found one match

# Check if it's the right time to print
found > N && printed <= K {
  # Printed once
}' file

Make sure you fill in pattern, N, and K as needed.

The first block will keep track of each time the pattern is found. Once that passes the N threshold, the second block starts printing each line. The second block will stop printing once the K threshold is reached.


you can use awk

awk 'd && k--&&k>=0; c>=3 && /pattern/{d=1;k=2} /pattern/{c++};' file

First /3/{c++} increments c value everytime it matches pattern. If c reach the count of 3 for example , then set a flag (d) , and set the number of lines after it (k=2). d && k--&&k>=0 means as long as k value if more than 0 and less than 2, print the lines.

  • Awk is a programming language like any other, you could use semantic variable names to make this clearer.
    – bschlueter
    May 25, 2019 at 20:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy