使用 grep 顯示文本中不同行上 3 個單字之間的文本

使用 grep 顯示文本中不同行上 3 個單字之間的文本

我想顯示 1 個文件中文字中 3 個單字之間的文字:

lalala
<ticket>
BASH is awesome
BASH is awesome1
</ticket>
lalalala
<ticket>
BASH is awesome2
BASH is awesome3
texttext
</ticket>
lololo
<ticket>
awesome
BASH is awesome4
BASH is awesome5
</ticket>
lalalla

我試試這個:

grep -Pzo '(?s)<ticket>.*\n.*awesome3.*\n.*</ticket>' file.txt

結果:

<ticket>
BASH is awesome
BASH is awesome1
</ticket>
lalalala
<ticket>
BASH is awesome2
BASH is awesome3
texttext
</ticket>
lololo
<ticket>
awesome
BASH is awesome4
BASH is awesome5
</ticket>

期望:

<ticket>
BASH is awesome2
BASH is awesome3
texttext
</ticket>

答案1

使用以下內容grep方法:

grep -Pzo '(?s)<ticket>[^<>]*?awesome3.*?</ticket>' file.txt

輸出:

<ticket>
BASH is awesome2
BASH is awesome3
texttext
</ticket>

*?- 非貪婪修飾符

相關內容