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.
4 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
-
1I don't think this is what he wants (if i understood his question correctly) Aug 21, 2011 at 3:51
-
I don't want it. It would only print last match(es).– raviAug 21, 2011 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
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.
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. May 25, 2019 at 20:29
grep 'PATTERN' FILENAME | tail -n +M
where M
is N+1
-
2It 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
-