如何根據模式輸出特定段落?

如何根據模式輸出特定段落?

我有一個範例文件如下:

# This is a test file. This is a test file. This is a test file  
This is a test file. This is a test file. This is a test file.  
This is a test file.

# Need to output just this paragraph.Need to output just this paragraph.  
Need to output just this paragraph TOO. Need to output just this paragraph.  
Need to output just this paragraph.

我需要輸出從“#”開始到該段落最後一句的第二段。

如何根據模式 grep 並輸出?假設文件有更多段落,我想輸出包含單字“TOO”的段落。

答案1

如果段落以空白行分隔:

awk -v RS= -v ORS='\n\n' /TOO/

空記錄分隔符號 ( RS) 表示段落模式其中記錄由空行序列分隔。

如果他們#分開了:

awk -v RS='#' '/TOO/ {print RS $0}'

或者

pcregrep -Mo '#[^#]*?TOO[^#]*'
  • -M對於多行grep
  • -o僅輸出匹配的部分

答案2

perl -00ne 'print if /TOO/'
  • -00表示段落模式(記錄由一個或多個空白行分隔)。

相關內容