grep 从固定文本开始,直到第一个空行

hei*_*sen 11 sed awk sort regular-expression

我有一个prova.txt这样的文件:

Start to grab from here: 1
fix1
fix2
fix3
fix4
random1
random2
random3
random4

extra1
extra2
bla

Start to grab from here: 2
fix1
fix2
fix3
fix4
random1546
random2561

extra2
bla
bla

Start to grab from here: 1
fix1
fix2
fix3
fix4
random1
random22131
Run Code Online (Sandbox Code Playgroud)

我需要从“开始抓住这里”到第一个空行。输出应该是这样的:

Start to grab from here: 1
fix1
fix2
fix3
fix4
random1
random2
random3
random4

Start to grab from here: 2
fix1
fix2
fix3
fix4
random1546
random2561

Start to grab from here: 1
fix1
fix2
fix3
fix4
random1
random22131
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,“开始在这里抓取”之后的行是随机的,因此 -A -B grep 标志不起作用:

cat prova.txt | grep "Start to grab from here" -A 15 | grep -B 15 "^$" > output.txt
Run Code Online (Sandbox Code Playgroud)

你能帮我找到一种方法来捕捉将被抓取的第一行(如“从这里开始抓取”),直到一个空行。我无法预测在“开始从这里抓取”之后我会有多少随机行。

任何兼容 Unix 的解决方案都值得赞赏(grep、sed、awk 比 perl 或类似的要好)。

编辑:经过@john1024 的精彩回应,我想知道是否有可能:

1°对块进行排序(根据从这里开始抓取:1然后1然后2)

2° 删除 4(按字母顺序随机)行 fix1,fix2,fix3,fix4 但始终为 4

3° 最终删除随机欺骗,如 sort -u 命令

最终输出应该是这样的:

# fix lines removed - match 1 first time
Start to grab from here: 1
random1
random2
random3
random4

#fix lines removed - match 1 second time
Start to grab from here: 1
#random1 removed cause is a dupe
random22131

#fix lines removed - match 2 that comes after 1
Start to grab from here: 2
random1546
random2561
Run Code Online (Sandbox Code Playgroud)

或者

# fix lines removed - match 1 first time and the second too
Start to grab from here: 1
random1
random2
random3
random4
#random1 removed cause is a dupe
random22131

#fix lines removed - match 2 that comes after 1
Start to grab from here: 2
random1546
random2561
Run Code Online (Sandbox Code Playgroud)

第二个输出比第一个更好。需要一些其他的 Unix 命令魔法。

Joh*_*024 17

使用 awk

尝试:

$ awk '/Start to grab/,/^$/' prova.txt
Start to grab from here: 1
random1
random2
random3
random4

Start to grab from here: 2
random1546
random2561

Start to grab from here: 3
random45
random22131
Run Code Online (Sandbox Code Playgroud)

/Start to grab/,/^$/定义一个范围。它从匹配的任何行开始,Start to grab并以^$紧随其后的第一个空行 , 结束。

使用 sed

有着非常相似的逻辑:

$ sed -n '/Start to grab/,/^$/p' prova.txt
Start to grab from here: 1
random1
random2
random3
random4

Start to grab from here: 2
random1546
random2561

Start to grab from here: 3
random45
random22131
Run Code Online (Sandbox Code Playgroud)

-n告诉 sed 不要打印任何东西,除非我们明确要求它。 /Start to grab/,/^$/p告诉它打印由/Start to grab/,/^$/.