Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question

migrated from Aug 29 '11 at 7:35

This question came from our site for professional and enthusiast programmers.

Did any of the answers work for you? – Dan Cecile Aug 23 '11 at 2:32

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
share|improve this answer
I don't think this is what he wants (if i understood his question correctly) – user31894 Aug 21 '11 at 3:51
I don't want it. It would only print last match(es). – ravi Aug 21 '11 at 5:12

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.

share|improve this answer

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.

share|improve this answer

You must log in to answer this question.