Используя grep; как мне показать N-е вхождение шаблона?

5234
tjt263

Использование grep; как я могу показать N- й случай шаблона?

Например; man sh |grep -A3 -- '-c'вернет несколько матчей.

Я мог бы хотеть выделить только 3- е вхождение, чтобы оно показывало:

-- -c Read commands from the command_string operand instead of from the standard input. Special parameter 0 will be set from the command_name operand and the positional parameters ($1, $2, etc.) set from the remaining argument operands. -- 

1

1 ответ на вопрос

2
John1024

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 count n by one. If n is three, then set f to three.

  • f

    If f is nonzero, then print the line and decrement f.

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.

Похожие вопросы