Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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 stackoverflow.com 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
add comment

3 Answers

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
1  
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
add comment

An alternative solution in awk:

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

More readably:

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

# Check for a pattern match
/pattern/ {
  found++
  # Found one match
}

# Check if it's the right time to print
found > N && printed <= K {
  print
  printed++
  # 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
add comment

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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.