The occurrence that you want is not the second occurrence; it is the third. To get the third occurrence of -c
with three lines of context:
$ man sh | awk '/-c/ f' -c Read commands from the command_string operand instead of from the standard input. Special param‐ eter 0 will be set from the command_name operand and the positional parameters ($1, $2, etc.) set from the remaining argument operands.
How it works
awk implicitly reads its input line by line. This script uses two variables. n
keeps track of how many times we have seen -c
. f
keeps track of how many lines we are supposed to print.
/-c/
If we reach a line containing
-c
, then increment the countn
by one. Ifn
is three, then setf
to three.f
If
f
is nonzero, then print the line and decrementf
.
Alternative solution
$ man sh | grep -A3 -m3 -- -c | tail -n4 -c Read commands from the command_string operand instead of from the standard input. Special param‐ eter 0 will be set from the command_name operand and the positional parameters ($1, $2, etc.) set from the remaining argument operands.
The -m3
option tells grep to return only the first three matches. tail -n4
returns the last four lines from among those matches. If the second and third match to -c
were within the context number of lines, though, this output may not be what you want.