sed - 打印字符串第 n 次出现之前的所有行

Ida*_*Ida 2 bash sed

假设我有:

content line 1
content line 2
blabla *my_pattern_str* (1st occurrence)
...
content line x 
blabla *my_pattern_str* (nth occurrence <- I want to print from the beginning line up to here)
content line y
content line y+1
...
Run Code Online (Sandbox Code Playgroud)

我想打印my_pattern_str之前的所有行(包括第 n 次出现) 。我如何使用sed(或类似的命令,如grepawk)来做到这一点?

Tom*_*ech 6

你可以用这个。该变量N是最大次数。它将处理文件的其余部分,但我认为这没什么大不了的:

awk -vN=2 'n<N;/my_pattern/{++n}' file
Run Code Online (Sandbox Code Playgroud)

每次匹配模式时都会增加一个计数器。只要计数器低于变量,就打印该行N