3

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
  • 1
    Did any of the answers work for you?
    – Dan Cecile
    Aug 23, 2011 at 2:32

4 Answers 4

5

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
3
  • 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.
    – Schlueter
    May 25, 2019 at 20:27
3

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.

0

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.

1
  • Awk is a programming language like any other, you could use semantic variable names to make this clearer.
    – Schlueter
    May 25, 2019 at 20:29
-1
grep 'PATTERN' FILENAME | tail -n +M

where M is N+1

2
  • 2
    It would help everyone, if you would please explain your answer. What does it do ? Why does it work ? Even link a reference to grep commands Aug 11, 2022 at 21:55
  • Looks similar to Adam's answer Aug 13, 2022 at 13:59

You must log in to answer this question.