gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 08:58:13 30 4
gpt4 key购买 nike

假设我有:

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
...

我想打印第 n 次出现的 my_pattern_str 之前的所有行,包括第 n 次出现的行。我如何使用 sed(或类似的命令,如 grepawk)执行此操作?

最佳答案

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

awk -vN=2 'n<N;/my_pattern/{++n}' file

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

关于bash - sed - 打印字符串第 n 次出现之前的所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25072891/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com