There is a big file containing a pattern which is repeated periodically in the file, I want to extract just a specific pattern after certain values of occurrence as well as the next N lines.
Here is an example but the numbers before members of the group
are not really existing.
input:
1 members of the group
...
...
2 members of the group
...
...
...
n members of the group
...
...
...
output:
85 members of the group
...
...
...
...
...
(85th match and the next 5 lines)
Best Answer
Here's one way with
awk
:Where
N
is the Nth line matchingPATTERN
andM
is the number of lines that follow. It sets a counter and when the Nth line matching is encountered it saves the line number. It then prints the lines from the currentNR
up toNR
+M.For the record, that's how you do it with
sed
(gnu sed
syntax):This is using the hold space to count.
Each time it encounters a line matching
PATTERN
it ex
changes buffers and checks if there are N-1 occurrences of\n
ewline character in the hold buffer. If the check is successful it ex
changes again, pulls in the next M lines with the$!N
command andp
rints the pattern space thenq
uits.Otherwise it just adds another
\n
ewline char to the hold space and ex
changes back.This solution is less convenient as it quickly becomes cumbersome when M is a big number and requires some
printf
-fu to build up ased
script (not to mention the pattern and hold space limits with somesed
s).