I have a huge log file and want to grep the first occurrence of a pattern, and then find another pattern right after this occurence.
For example:
123
XXY
214
ABC
182
558
ABC
856
ABC
In my example, I would like to find 182
and then find the next occurrence of ABC
The first occurrence is simple:
grep -n -m1 "182" /var/log/file
This outputs:
5:182
How do I find the next occurrence of ABC?
My idea was to tell grep
to skip the first n
lines (in the above example n=5
), based on the line number of 182. But how do I do that?
Best Answer
With
sed
you can use a range andq
uit input at a single completion:Similarly w/ GNU
grep
you can split the input between twogrep
s:... which prints...
... to signify that the first
grep
found a-F
ixed-string literal,-x
entire-line 182 match 5 lines from the start of its read, and the second found a similarly typed ABC match 2 lines from the start of its read - or 2 lines after the firstgrep
quit reading at line 5.From
man grep
:I used a here-document for the sake of reproducible demonstration, but you should probably do:
It will also work with other shell compound-command constructs like: